原理:
1. 对原始参数名加前辍标示为加密参数名,传输前对其参数值加密。
2. 获取时,先检查原始名称是否存在,如果不存在则查找是否有加密前辍的参数名,并对其解密。
public class RequestUtil {
/**安全名称前辍*/
public static final String SAFE_PREFIX = "__";
/**
* 转换为安全参数名称
* @param name
* @return
*/
static
public String toSafeParamName(String name){
if(null==name || "".equals(name)){
throw new NullPointerException("name is null");
}
return SAFE_PREFIX+name;
}
/**
* 转换为一个安全的字符串参数
* @param value
* @param eKey 密钥
* @return
*/
static
public String toSafeStrParam(String value, String eKey){
return null!=value? DesUtil.encode(value, eKey): value;
}
/**
* 还原(安全转换过的)字符串
* @param value
* @param eKey
* @return
*/
static
public String recoveryStr(String value, String eKey){
if(null != value && value.length()>2){
return DesUtil.decode(value, eKey);
}
return value;
}
/**
* 获取请求字符串参数
* 依parameter-attribute-session序查找
* @param request
* @param name 如果在参数中找不到name的参数,则尝试找SAFE_PREFIX+name
* @param eKey 密钥
* @return
*/
static
public String getRequestStrParam(HttpServletRequest request, String name, String eKey){
String name$ = SAFE_PREFIX+name;
String value=request.getParameter(name);
if(null == value){
value = request.getParameter(name$);
value = recoveryStr(value, eKey);
}
if(null == value){
if(null == (value=(String)request.getAttribute(name))){
value = (String)request.getAttribute(name$);
value = recoveryStr(value, eKey);
}
}
if(null == value){
HttpSession session = request.getSession();
if(null!=session){
if(null == (value=(String)session.getAttribute(name))){
value = (String)session.getAttribute(name$);
value = recoveryStr(value, eKey);
}
}
}
return value;
}
}
测试:
servlet(spring mvc)
@Controller
@RequestMapping("/t")
public class TestController {
static final String ENC_KEY = "..............";
@RequestMapping("test1")
@ResponseBody
public String test1(HttpServletRequest request){
String value = RequestUtil.getRequestStrParam(request, "name", ENC_KEY);
return value;
}
}
生成加密url
public class Test2 {
private static String ENC_KEY = "。。。。。。。。。。。。。";
@Test
public void t1(){
String req_name = "name";
String req_value = "Tom";
String url = String.format("http://127.0.0.1:8080/t/test1?%s=%s",
RequestUtil.toSafeParamName(req_name),
RequestUtil.toSafeStrParam(req_value, ENC_KEY));
System.out.println(url);
}
}