使用RequestBodyAdvice和ResponseAdice实现
RequestBodyAdvice
@Slf4j
@RestControllerAdvice
public class RequestAdvice implements RequestBodyAdvice {
@Override
public Object handleEmptyBody(Object body,
HttpInputMessage inputMessage,
MethodParameter parameter,
Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
return body;
}
@Override
public boolean supports(MethodParameter methodParameter,
Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
// 当且仅当请求为POST 且带有@EncryAndDecry 注解的请求会被处理
return methodParameter.hasParameterAnnotation(RequestBody.class) && methodParameter.hasMethodAnnotation(EncryAndDecry.class);
}
@SneakyThrows
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage,
MethodParameter parameter,
Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
EncryAndDecry encryAndDecry = parameter.getMethodAnnotation(EncryAndDecry.class);
// 请求解密
if (encryAndDecry.decry()) {
// 和前端交互时,数据格式待定,暂已{"param":"xxxx"}为准,xxx为加密后的对象
String body = IOUtils.toString(inputMessage.getBody(),"utf-8");
JSONObject jsonObject = JSONObject.parseObject(body);
String param = jsonObject.getString("param");
if (!jsonObject.containsKey("param") || Strings.isNullOrEmpty(param)) {
throw new IOException("未获取到入参");
} else {
String decryStr = "";
try {
log.info("开始解密:{}",jsonObject);
decryStr = EncryptionUtil.AesDecrypt(param);
if (Strings.isNullOrEmpty(decryStr)) {
throw new IOException("解密失败");
}
log.info("解密完成:{}", decryStr);
} catch (Exception e) {
throw new IOException("解密失败");
}
InputStream inputStream = new ByteArrayInputStream(decryStr.getBytes());
return new DecryptHttpInputMessage(inputMessage.getHeaders(), inputStream);
}
}
return inputMessage;
}
@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return body;
}
static class DecryptHttpInputMessage implements HttpInputMessage{
HttpHeaders headers;
InputStream body;
public DecryptHttpInputMessage(HttpHeaders headers,InputStream body){
this.headers = headers;
this.body = body;
}
@Override
public InputStream getBody() throws IOException {
return body;
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
}
}
ResponseAdice
@Slf4j
@ControllerAdvice
public class ResponseAdice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return returnType.hasMethodAnnotation(EncryAndDecry.class);
}
@Override
public Object beforeBodyWrite(Object body,
MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request,
ServerHttpResponse response) {
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(body);
EncryAndDecry encryAndDecry = returnType.getMethodAnnotation(EncryAndDecry.class);
// 有body且启用加密时
if (jsonObject.containsKey("body") && encryAndDecry.encry()) {
String encyStr = "";
try{
log.info("开始对{}进行加密",jsonObject.getString("body"));
encyStr = EncryptionUtil.AesEncryption(jsonObject.getString("body"));
jsonObject.replace("body", encyStr);
} catch (Exception e) {
jsonObject.replace("errCode", "e9999");
jsonObject.replace("errMsg", "加密失败");
log.error("加密失败:{}", jsonObject);
}
}
return jsonObject;
}
}
EncryAndDecry
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EncryAndDecry {
/**
* 返参是否需要加密
* @return
*/
boolean encry() default false;
/**
* 入参是否需要解密
* @return
*/
boolean decry() default false;
}
使用方式
默认传参命名为:param
@EncryAndDecry(encry = true , decry = true)
引入依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
加解密方式
@Slf4j
public class EncryptionUtil {
private static final String SECRET_KEY = "***32位字符串***";
//偏移量字符串必须是16位 当模式是CBC的时候必须设置偏移量
private static final String IV = "***16位***";
private static final String ALGORITHM = "AES";
//算法/模式/补码方式
private static final String ALGORITHM_PROVIDER = "AES/CBC/PKCS5Padding";
public static String getKey(String keyType) {
if ("param".equals(keyType)) {
return SECRET_KEY;
}
return SECRET_KEY;
}
/**
* 返参加密
* @param content
* @return
* @throws Exception
*/
public static String AesEncryption(String content) throws Exception {
return encryption(content, SECRET_KEY);
}
public static String encryption(String content, String key) throws Exception {
byte[] bytes = key.getBytes("utf-8");
String AESContent = byteToHexString(encrypt(content, bytes));
return AESContent;
}
/**
* 入参解密
* @param content
* @return
* @throws Exception
*/
public static String AesDecrypt(String content) throws Exception {
return decrypt(content, SECRET_KEY);
}
public static String decrypt(String content, String key) throws Exception {
byte[] bytes = key.getBytes("utf-8");
String AESContent = new String(decrypt(content, bytes));
return AESContent;
}
public static String byteToHexString(byte[] src) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xff;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
sb.append("0");
}
sb.append(hv);
}
return sb.toString();
}
public static byte[] encrypt(String src, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
IvParameterSpec ivParameterSpec = getIv();
Cipher cipher = Cipher.getInstance(ALGORITHM_PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
byte[] cipherBytes = cipher.doFinal(src.getBytes(Charset.forName("utf-8")));
return cipherBytes;
}
public static IvParameterSpec getIv() throws UnsupportedEncodingException {
IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes("utf-8"));
return ivParameterSpec;
}
public static byte[] decrypt(String src, byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
IvParameterSpec ivParameterSpec = getIv();
Cipher cipher = Cipher.getInstance(ALGORITHM_PROVIDER);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
byte[] hexBytes = hexStringToBytes(src);
byte[] plainBytes = cipher.doFinal(hexBytes);
return plainBytes;
}
public static byte[] hexStringToBytes(String hexString) {
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] b = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
b[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return b;
}
private static byte charToByte(char c) {
return (byte) IV.indexOf(c);
}
}