cookie加密解密全过程,使用filter实现自动登录

来源:互联网 发布:如何让牙齿整齐 知乎 编辑:程序博客网 时间:2024/05/16 05:55

相信每一个程序员在做网站开发的时候都会遇到这个问题:网站实现自动记住密码,下次自动登录

废话不多说闭嘴


1、工具类(对cookie加密,保存到本地)

package com.itzhongc.util;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;


import com.itzhongc.share.user.entity.User;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;




public class UserCookieUtil {
// 保存cookie的cookieName
private final static String cookieDomainName = "xxx";   //自己随便定义
// 加密cookie时的网站自定码
private final static String webKey = "xxx";   //自己随便定义
// 设置cookie有效期是两个星期,根据需要自定义
private final static long cookieMaxAge = 60 * 60 * 24 * 7 * 2;


// 保存Cookie到客户端
// 传递进来的user对象中封装了在登陆时填写的用户名与密码
public static void saveCookie(User user, HttpServletResponse response) {
// cookie的有效期至(到哪一天)
long validTime = System.currentTimeMillis() + (cookieMaxAge * 1000);
// MD5加密用户详细信息(其实就是把当前用户加密一下,后面判断是否是同一个用户)
String cookieValueWithMd5 = getMD5(user.getUser_email() + ":"+ user.getUser_password() + ":" + validTime + ":" + webKey);
// 将要被保存的完整的Cookie值
String cookieValue = user.getUser_email() + ":" + validTime +":"+cookieValueWithMd5;
// 再一次对Cookie的值进行BASE64编码
String cookieValueBase64 = new String(Base64.encode(cookieValue.getBytes()));
// 开始保存Cookie(cookie是网站名和值)
Cookie cookie = new Cookie(cookieDomainName, cookieValueBase64);
// 存两年(这个值应该大于或等于validTime)
cookie.setMaxAge(60 * 60 * 24 * 365 * 2);
// cookie有效路径是网站根目录
cookie.setPath("/");
// 向客户端写入
response.addCookie(cookie);
}


// 用户注销时,清除Cookie
public static void clearCookie(HttpServletResponse response) {
//创建一个空cookie添加,覆盖原来的达到清除目的
Cookie cookie = new Cookie(cookieDomainName, null);
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
}


// 获取Cookie组合字符串的MD5码的字符串
public static String getMD5(String value) {
String result = null;
try {
byte[] valueByte = value.getBytes();
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(valueByte);
result = toHex(md.digest());
} catch (NoSuchAlgorithmException e2) {
e2.printStackTrace();
}
return result;
}


// 将传递进来的字节数组转换成十六进制的字符串形式并返回
private static String toHex(byte[] buffer) {
StringBuffer sb = new StringBuffer(buffer.length * 2);
for (int i = 0; i < buffer.length; i++) {
sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(buffer[i] & 0x0f, 16));
}
return sb.toString();
}
}


2、创建Filter(进行对登录用户判断cookie是否可用)

关键代码(重要,没有这段代码解密无法实现自动登录)

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
Cookie[] cookies = req.getCookies();
ServletContext sc = req.getSession().getServletContext();
XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
userService = (UserService) cxt.getBean("userService");//获取service操作对象
if(cookies!=null){
for (Cookie cookie : cookies) {
if(cookie.getName().equals("xxx")){//获取签名是否为我们网站的cookie(工具类中自定义的名称)
byte[] decode = Base64.decode(cookie.getValue());//使用base64解密得到数组
String cookieValue = new String(decode);
String[] split = cookieValue.split(":");//截取
if(split.length==3){//长度不足3就是非法登录
Long long1 = new Long(split[1]);
if(System.currentTimeMillis()<long1){//判断cookie是否在有效期内
String user_email = split[0];//获取邮箱地址
User user = userService.getPassword(user_email);//根据邮箱地址查询数据库是否有这个对象
//获取md5加密后的数据与cookie中的数据对比,如果相同则自动登录,否则重新登录
String md5 = UserCookieUtil.getMD5(user.getUser_email()+":"+user.getUser_password()+":"+long1+":"+"itzhongc");
if(md5.equals(split[2])){//说明验证成功!
req.getSession().setAttribute("user", user);
}
}
}
}
}
}
chain.doFilter(req, res);

注意:

3、Filter配置(注意需要配置在struts2配置的前面)


即使没人看我也要坚持每天更新!!!

原创粉丝点击