在系统登录的时候,我们需要对密码进行加密处理,而这个加密在别的地方也能用到,因此可以将加密操作抽象出来,放到通用工具模块中,再如前端发送给后端的请求,一种是普通的http请求,另一种是Ajax请求,在不少给前端回传数据的时候需要判断请求是否是Ajax请求,因此也可以抽象出来成为一个工具方法。
1、MD5加密
在尚筹网项目前期开发中,加密方式采用MD5加密,后期整合SpringSecurity后,使用其自带的加盐加密。
/**
* MD5加密
* @param source 明文
* @return 密文
*/
public static String encryptMd5(String source){
//判断字符串是否合法
if(source == null){
throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
}
try {
//加密
String algorithm = "md5";
byte[] input = source.getBytes();
byte[] output = MessageDigest.getInstance(algorithm).digest(input);
int signum = 1;
BigInteger bigInteger = new BigInteger(signum, output);
int radix = 16;
return bigInteger.toString(radix).toUpperCase();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("没有这个加密算法");
}
}
2、请求判断
普通请求和Ajax请求在消息头有些许不同,Ajax请求的消息头中包含有"application/json"以及"XMLHttpRequest",因此将消息头中的这两个参数取出来看看就是:
/**
* 判断当前请求是否是Ajax请求
* @param request 请求对象
* @return true:当前请求为Ajax请求;false:当前请求为普通请求;
*/
public static boolean judgeRequestType(HttpServletRequest request){
//1、获取请求消息头
String acceptHeader = request.getHeader("Accept");
String xRequestHeader = request.getHeader("X-Requested-With");
//2、判断
return (acceptHeader!=null && acceptHeader.contains("application/json")) || "XMLHttpRequest".equals(xRequestHeader);
}