前后端数据传输加密(一)
1.AES对称加密a.前端加解密<script src="https://cdn.bootcss.com/crypto-js/3.1.9-1/crypto-js.min.js"></script>/*** 加密**/functionencrypt(value,key) {var tempValue = JSON.stringify(value);var tempKey =
·
1.AES对称加密
加密流程:
1.前端调用接口/web/security/v1/getAesKey 并将其保存在sesssionStrage中
2.后端在前端调用/web/security/v1/getAesKey时,生成AES密钥并保存在session中,并返回给前端
3.前端访问其他接口传入的参数都用此AES密钥加密,接收到的响应数据都用此AES密钥解密,可以拦截器,对所有请求和响应加解密
4.后端和前端一样用此AES密钥进行加解密
a.前端加解密
<script src="https://cdn.bootcss.com/crypto-js/3.1.9-1/crypto-js.min.js"></script> /** * 加密 **/ function encrypt(value,key) { var tempValue = JSON.stringify(value); var tempKey = CryptoJS.enc.Utf8.parse(key); var srcs = CryptoJS.enc.Utf8.parse(tempValue); var encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding:CryptoJS.pad.Pkcs7 }); var encryptedValue = encrypted.toString(); return encryptedValue; } /** *解密 **/ function decrypt(value,key) { var keyStr = CryptoJS.enc.Utf8.parse(key) var decrypt = CryptoJS.AES.decrypt(value, keyStr, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }) return CryptoJS.enc.Utf8.stringify(decrypt).toString() }
b.后端加解密
public class AesEncrypt {
/**
* 加密
*
* @param value数据
* @param key 密钥
* @return 加密后内容
*/
public static byte[] encrypt(byte[] value, String key) throw Exception{
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("UTF-8"), "AES"));
return cipher.doFinal(value);
}
/**
* 解密
*
* @param value数据
* @param key 密钥
* @return 解密后内容
*/
public static byte[] decrypt(byte[] value, String key) throw Exception {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
//使用密钥初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
//执行操作
return cipher.doFinal(value);
}
}
c.后端拦截代码实现
/**
* 请求过滤器,记得注册
**/
public EncryptFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
String uri = request.getRequestURI();
LOGGER.debug("进入加解密过滤器,URI:{}", uri);
HttpServletResponse response = (HttpServletResponse) servletResponse;
AesHttpServletRequestWrapper aesHttpServletRequestWrapper = new AesHttpServletRequestWrapper(request);
filterChain.doFilter(aesHttpServletRequestWrapper, response);
}
}
/**
* (1)请求拦截,解密
**/
public class AesHttpServletRequestWrapper extends HttpServletRequestWrapper {
private String bodyContent;
private Parameters parameters = new Parameters();
private HttpServletRequest request;
public AesHttpServletRequestWrapper (HttpServletRequest request) {
request = request;
initWrapper();
}
private void initWrapper() {
this.parameters.setCharset(charset);
readBodyBytes();
this.parseParameterMap();
}
private void readBodyBytes() {
if (this.bodyContent == null) {
try {
byte[] bodyBytes = readInputBody(request.getInputStream());
this.bodyContent = new String(AesEncrypt.decrypt(bodyBytes), charset);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private byte[] readInputBody(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
byteArrayOutputStream.flush();
return byteArrayOutputStream.toByteArray();
}
@Override
public String getQueryString() {
return queryString;
}
@Override
public String getParameter(String name) {
String[] values = getParameterValues(name);
return values == null || values.length == 0 ? null : values[0];
}
@Override
public int getContentLength() {
return bodyContent.getBytes(charset).length;
}
@Override
public long getContentLengthLong() {
return bodyContent.getBytes(charset).length;
}
@Override
public Map<String, String[]> getParameterMap() {
if (paramsMap == null) {
paramsMap = new HashMap<>();
Enumeration<String> nameEnum = this.parameters.getParameterNames();
while (nameEnum.hasMoreElements()) {
String name = nameEnum.nextElement();
paramsMap.put(name, getParameterValues(name));
}
}
return paramsMap;
}
@Override
public Enumeration<String> getParameterNames() {
return this.parameters.getParameterNames();
}
@Override
public String[] getParameterValues(String name) {
return parameters.getParameterValues(name);
}
}
/**
* (2) 响应拦截 加密
**/
@ControllerAdvice
public class AesResponseAdvice implements ResponseBodyAdvice<Object> {
private static final String AES_KEY= "AES_KEY";
@Override
public Object beforeBodyWrite(Object body, MethodParameter methodParameter,
MediaType mediaType,
Class<? extends HttpMessageConverter<?>> converterClass,
ServerHttpRequest serverHttpRequest,
ServerHttpResponse serverHttpResponse) {
ServletServerHttpRequest request = (ServletServerHttpRequest) serverHttpRequest;
if (body != null) {
ServletServerHttpResponse response = (ServletServerHttpResponse) serverHttpResponse;
try {
byte[] contentBytes = null;
contentBytes = String.valueOf(body).getBytes(Charset.forName("UTF-8"));
Object aesKey = request.getServletRequest().getSession().getAttribute(AES_KEY);
body = AesEncrypt.encrypt(contentBytes,String.value(aesKey));
} catch (IOException e) {
LOGGER.error("加密数据失败", e);
}
}
return body;
}
}
更多推荐
已为社区贡献3条内容
所有评论(0)