原标题:技术分享:COOKIE 防伪造 防修改
主要防止非法用户修改COOKIE信息,以及COOKIE的超时时间
传统COOKIE存储,COOKIE(name, value),value很容易就被篡改。
防修改COOKIE存储,COOKIE(name, value+“”+ signToken+“”+saveTime+“”+maxTime)
signToken :签名密钥 由md5(value+saveTime+maxTime+”自定义密钥“)生成
saveTime:COOKIE创建时间
maxTime:COOKIE超时时间
设置COOKIE
public static void put(HttpServletResponse response, String key, String value, int maxTime) {
String pwdKey = white_yu; //自定义密钥
String saveTime = System.currentTimeMillis() + ;
String signToken = md5(pwdKey, saveTime, maxTime + , value);
String COOKIEValue = signToken + + saveTime + + maxTime
+ + value;
COOKIE COOKIE = new COOKIE(key,COOKIEValue);
COOKIE.setMaxAge(maxTime);
response.addCOOKIE(COOKIE);
}
获取COOKIE
public static String getCOOKIE(String COOKIEValue) {
String pwdKey = white_yu; //自定义密钥
if (StringUtils.isNotBlank(COOKIEValue)) {
String COOKIEStrings[] = COOKIEValue.split();
if (null != COOKIEStrings 4 == COOKIEStrings.length) {
String signToken = COOKIEStrings[0];
String saveTime = COOKIEStrings[1];
String maxTime = COOKIEStrings[2];
String value = COOKIEStrings[3];
String sign = md5(pwdKey, saveTime, maxTime, value);
// 保证 COOKIE 不被人为修改
if (sign.equals(signToken)) {
long stime = Long.parseLong(saveTime);
long maxtime = Long.parseLong(maxTime) * 1000;
// 查看是否过时
if ((stime + maxtime) - System.currentTimeMillis() 0) {
return value;
}
}
}
}
return null;
责任编辑: