对于安全性较高的网站,请求参数传输可能会加密城密文,在进行传输,这里,小编给大家提供一个简单的使用AES对请求参数进行加密的代码实现(普通get/post以及application/json的post请求),放代码吧。
首先定义一些常量:
package cn.wjp.mydaily.common.filter;
public class HttpConst {
/**
* 几种常见的Content-Type
*/
public static final String FORM_URLENCODED_CONTENT_TYPE ="application/x-www-form-urlencoded";
public static final String JSON_CONTENT_TYPE = "application/json";
public static final String MULTIPART_CONTENT_TYPE = "multipart/form-data";
/**
* 常见的post/get请求方式
*/
public static final String POST_METHOD = "post";
public static final String GET_METHOD = "get";
public static final String OPTIONS_METHOD = "options";
}
接下来是AES加密解密的工具类:
package cn.wjp.mydaily.common.filter;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* AES加密、解密
* @author wjp
*
*/
public class AESCipher {
//偏移量
private static final String IV_STRING = "16-Bytes--String";//长度为16的字符串
//私钥
public static final String KEY = "key1234561111111";//长度为16的字符串
public static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
/**
* 加密方法
* @param content 加密内容
* @param key 加密公钥 16-Bytes--String
* @return
*/
public static String encryptAES(String content, String key)
throws Exception {
byte[] byteContent = content.getBytes("UTF-8");
// 这里的 key 不可以使用 KeyGenerator、SecureRandom、SecretKey 生成
byte[] enCodeFormat = key.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
// 指定加密的算法、工作模式和填充方式
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encryptedBytes = cipher.doFinal(byteContent);
// 同样对加密后数据进行 base64 编码
Encoder encoder = Base64.getEncoder();
return encoder.encodeToString(encryptedBytes);
}
/**
* 解密算法
* @param content 解密内容
* @param key 加密公钥 16-Bytes--String
* @return
*/
public static String decryptAES(String content, String key) {
try {
// base64 解码
Decoder decoder = Base64.getDecoder();
byte[] encryptedBytes = decoder.decode(content);
byte[] enCodeFormat = key.getBytes();
SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, "AES");
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
byte[] result = cipher.doFinal(encryptedBytes);
return new String(result, "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
好了,万事俱备,接下来该过滤器登场了:
package cn.wjp.mydaily.common.filter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import javax.servlet.*;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* 对请求参数做处理
*/
public class ParamsFilter implements Filter {
private static final String DECRYPT_PARAM_NAME = "decrypt";//请求参数包含的是否加密的字段
private static final String DEFAULT_DECRYPT_TYPE = "AES";//默认加密的类型
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String contentType = request.getContentType();//获取contentType请求头
String method = request.getMethod();//获取请求方法 post/get
//1 处理get请求 get请求的Content-Type一般为application/x-www-form-urlencoded 或者 text/html
if (method.trim().equalsIgnoreCase(HttpConst.GET_METHOD)) {
String decrypt = request.getParameter(DECRYPT_PARAM_NAME);
if(decrypt==null||decrypt.trim().isEmpty()){
chain.doFilter(request, response);
return;
}
HttpServletRequestNormalWrapper wrapperRequest = new HttpServletRequestNormalWrapper(request);
Map<String, String[]> parameterMap = wrapperRequest.getParameterMap();
parameterMap = decryptParamForNormalRequest(parameterMap,decrypt);
wrapperRequest.setParameterMap(parameterMap);
chain.doFilter(wrapperRequest, response);
return;
}
//2 处理post请求 只处理application/x-www-form-urlencoded application/json,对于multipart/form-data,直接放行
if (method.trim().equalsIgnoreCase(HttpConst.POST_METHOD)) {
if (contentType.trim().toLowerCase().contains(HttpConst.MULTIPART_CONTENT_TYPE)) {
chain.doFilter(request, response);
return;
}
//处理application/x-www-form-urlencoded
if (contentType.trim().toLowerCase().contains(HttpConst.FORM_URLENCODED_CONTENT_TYPE)) {
String decrypt = request.getParameter(DECRYPT_PARAM_NAME);
if(decrypt==null||decrypt.trim().isEmpty()){
chain.doFilter(request, response);
return;
}
HttpServletRequestNormalWrapper wrapperRequest = new HttpServletRequestNormalWrapper(request);
Map<String, String[]> parameterMap = wrapperRequest.getParameterMap();
parameterMap = decryptParamForNormalRequest(parameterMap,decrypt);
wrapperRequest.setParameterMap(parameterMap);
chain.doFilter(wrapperRequest, response);
return;
}
//处理application/json
if (contentType.trim().toLowerCase().contains(HttpConst.JSON_CONTENT_TYPE)) {
HttpServletRequestBodyReaderWrapper requestWrapper = new HttpServletRequestBodyReaderWrapper(request);
String body = requestWrapper.getBody();
if (body == null || body.trim().isEmpty()||body.trim().equalsIgnoreCase("{}")) {
chain.doFilter(requestWrapper, response);
return;
}
Map<String, Object> map = JSON.parseObject(body, new TypeReference<Map<String, Object>>() {});
String decrypt = (String)map.get(DECRYPT_PARAM_NAME);
if(decrypt==null||decrypt.trim().isEmpty()){
chain.doFilter(requestWrapper, response);
return;
}
body = decryptParamForPostJsonRequest(body,decrypt);
requestWrapper.setBody(body);
chain.doFilter(requestWrapper, response);
return;
}
}
chain.doFilter(request, response);
return;
}
/**
* 字符串解密
*
* @param value
* @return
*/
public String decryptParam(String value,String decryptType) {
if(decryptType.trim().equalsIgnoreCase(DEFAULT_DECRYPT_TYPE)){
return AESCipher.decryptAES(value,AESCipher.KEY);
}else{
return value + "+++";
}
}
/**
* 普通的post/get请求
*
* @param parameterMap
*/
public Map<String, String[]> decryptParamForNormalRequest(Map<String, String[]> parameterMap,String decryptType) {
Map<String, String[]> decryptMap = new HashMap<>();
if (parameterMap == null || parameterMap.size() == 0) {
return decryptMap;
}
for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
String key = entry.getKey();
if(key==null||key.trim().equalsIgnoreCase(DECRYPT_PARAM_NAME)){
continue;
}
String[] value = entry.getValue();
//String decryptKey = decodeParam(key,decryptType);
String[] decryptValue = null;
if (value != null && value.length > 0) {
decryptValue = new String[value.length];
for (int i = 0; i < value.length; i++) {
decryptValue[i] = decryptParam(value[i],decryptType);
}
}
decryptMap.put(key, decryptValue);
}
//打印用
StringBuffer printStr = new StringBuffer();
for (Map.Entry<String, String[]> entry1 : decryptMap.entrySet()) {
printStr.append(entry1.getKey()).append("=").append(Arrays.asList(entry1.getValue())).append("&");
}
System.out.println("ParamsFilter:发送的请求参数:" + JSON.toJSONString(printStr));
return decryptMap;
}
/**
* post的application/json请求
*
* @param body
*/
public String decryptParamForPostJsonRequest(String body,String decryptType) {
String decryptBody = "{}";
if (body == null || body.trim().isEmpty()||body.trim().equalsIgnoreCase("{}")||!body.trim().contains(":")) {
return decryptBody;
}
Map<String, Object> map = JSON.parseObject(body, new TypeReference<Map<String, Object>>() {
});
if (map == null || map.size() == 0) {
return decryptBody;
}
Map<String, Object> decryptMap = new HashMap<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
if(key==null||key.trim().equalsIgnoreCase(DECRYPT_PARAM_NAME)){
continue;
}
Object value = entry.getValue();
String valueStr = String.valueOf(value);
if (valueStr == null || valueStr.trim().isEmpty() || valueStr.trim().equalsIgnoreCase("null")) {
valueStr = null;
}
decryptMap.put(key, decryptParam(valueStr,decryptType));
}
decryptBody = JSON.toJSONString(decryptMap);
System.out.println("ParamsFilter:发送的请求参数:" + decryptBody);
return decryptBody;
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig arg0) {
}
}
打完收工~