发表于: 2017-11-20 20:48:30
1 687
MD5加密(不可逆加密)
工具类:
package org.shunly.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
public static String md5Encode(String string) throws Exception {
MessageDigest md5 = null;
try {
//MessageDigest初始化
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
//得到UTF-8字节编码的字节数组
byte[] Array = string.getBytes("UTF-8");
//哈希计算
byte[] md5Byte = md5.digest(Array);
//填充
StringBuffer stringBuffer = new StringBuffer();
for(byte b : md5Byte){
int bt = b & 0xff;
if(bt < 16) {
stringBuffer.append(0);
}
stringBuffer.append(Integer.toHexString(bt));
}
return stringBuffer.toString();
}
}
测试类:
package org.shunly.test;
import static org.shunly.util.MD5Util.md5Encode;
public class MD5Test {
public static void main(String args[]) throws Exception {
String s = new String("212asdad");
System.out.println("加密前:" + s);
System.out.println("加密后:" + md5Encode(s));
}
}
结果:
DES(可逆加密)
public class DesUtil {
private static final String ENCRYPT_TYPE = "DES";
private static String defaultKey = "";// 字符串默认键值
private Cipher encryptCipher = null;// 加密工具
private Cipher decryptCipher = null;// 解密工具
public DesUtil() throws Exception {
this(defaultKey);
}
/**
* 指定密钥构造方法
*
* @param strKey
* 指定的密钥
* @throws Exception
*/
public DesUtil(String strKey) throws Exception {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
Key key = getKey(strKey.getBytes());
encryptCipher = Cipher.getInstance(ENCRYPT_TYPE);
encryptCipher.init(Cipher.ENCRYPT_MODE, key);
decryptCipher = Cipher.getInstance(ENCRYPT_TYPE);
decryptCipher.init(Cipher.DECRYPT_MODE, key);
}
/**
* 加密字节数组
*
* @param arr
* 需加密的字节数组
* @return 加密后的字节数组
* @throws Exception
*/
private byte[] encryptStr(byte[] arr) throws Exception {
return encryptCipher.doFinal(arr);
}
/**
* 加密字符串
*
* @param strIn
* 需加密的字符串
* @return 加密后的字符串
* @throws Exception
*/
public String encrypt(String strIn) throws Exception {
return StrConvertUtil.byteArrToHexStr(encryptStr(strIn.getBytes()));
}
/**
* 解密字节数组
*
* @param arr
* 需解密的字节数组
* @return 解密后的字节数组
* @throws Exception
*/
private byte[] decryptStr(byte[] arr) throws Exception {
return decryptCipher.doFinal(arr);
}
/**
* 解密字符串
*
* @param strIn
* 需解密的字符串
* @return 解密后的字符串
* @throws Exception
*/
public String decrypt(String strIn) throws Exception {
return new String(decryptStr(StrConvertUtil.hexStrToByteArr(strIn)));
}
/**
* 从指定字符串生成密钥,密钥所需的字节数组长度为8位。不足8位时后面补0,超出8位只取前8位
*
* @param arrBTmp
* 构成该字符串的字节数组
* @return 生成的密钥
*/
private Key getKey(byte[] arrBTmp) {
byte[] arrB = new byte[8];// 创建一个空的8位字节数组(默认值为0)
// 将原始字节数组转换为8位
for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
arrB[i] = arrBTmp[i];
}
Key key = new javax.crypto.spec.SecretKeySpec(arrB, ENCRYPT_TYPE);// 生成密钥
return key;
}
}
测试类
加密用户名和登录时间的测试,用","分隔
public static void main(String args[]) throws Exception {
String str = "sadaasdas";
Long time = System.currentTimeMillis();
String s = str + "," + time;
System.out.println("原文:" + s);
DesUtil desUtil = new DesUtil();
String Token = desUtil.encrypt(s);
System.out.println("加密:" + Token);
String dec = desUtil.decrypt(Token);
System.out.println("解密:" + dec);
String[] Arrs = dec.split(",");
String user1 = Arrs[0];
String time1 = Arrs[1];
System.out.println("user:" + user1 + " time:" + time1);
}
结果:
添加拦截器
/u/前缀的进行拦截
<!--拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/u/*"/>
<bean class="org.shunly.util.Interceptor"/>
</mvc:interceptor>
</mvc:interceptors>
在Controller类的t11前面加个/u
@RequestMapping(value = "/u/t11", method = RequestMethod.GET)
使用DES对用户ID和登录时间加密,生成Token,放入Cookie中
//用户登录时间
Long time = System.currentTimeMillis();
user.setLogintime(time);
logger.info("login time:" + time);
//DES加密用户名和时间
String string = user.getUsername() + "," + time;
String token = desUtil.encrypt(string);
//存入cookie
Cookie cookie = new Cookie("token", token);
cookie.setMaxAge(20*60);//20分钟的有效期
cookie.setPath("/");//路径
response.addCookie(cookie);
重写一个preHandle方法进行cookie验证
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
Cookie[] cookies = httpServletRequest.getCookies();
if (null == cookies) {
//无cookies直接拦截
return false;
} else {
//提取cookies中name为token的值,
for(Cookie cookie : cookies){
if(cookie.getName().equals("token")){
//通过.分离cookie的值
String[] cook = cookie.getValue().split(".");
//取得存放在cookie中的name
String name = desUtil.decrypt(cook[0]);
//判断数据库中是否有name属性的用户
if(userService.judgeUser(name) != null){
Long time = Long.parseLong(desUtil.decrypt(cook[1]));
if ((new Date().getTime()-time)<=1000*20*60)//20分钟之内可以免登录,当前时间减去登陆时间
return true;
}
}
}
}
//没有cookie直接返回登陆页面
httpServletRequest.getSession().setAttribute("tips","请先登录");
httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login");
return false;
}
评论