springboot使用自定义注解实现接口返回结果加密

springboot使用自定义注解实现接口返回结果加密

1、编写自定义注解



import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public  @interface Encrypt {

}

2、 AES加密工具类

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class EncryptionUtils {



        private static final String ALGORITHM = "AES";
        private static final String SECRET_KEY = "**********."; // 替换为您自己的密钥

    /**
     * 加密
     * @param data
     * @return
     */
    public static String encrypt(String data) {
        try {
            SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 解密
     * @param encryptedData
     * @return
     */
        public static String decrypt(String encryptedData) {
        try {
            SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

3、 实现ResponseBodyAdvice接口

 ResponseBodyAdvice接口用于对响应体进行全局处理。它提供了在响应返回前和后对响应进行修改或增强的能力。
 下面是一个简单的示例,演示如何使用 ResponseBodyAdvice 对响应进行加密处理;
import cn.hutool.core.util.ObjectUtil;
import cn.lili.common.vo.ResultMessage;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class EncryptResponse  implements ResponseBodyAdvice<ResultMessage> {
    /**
     *   判断是否支持对该方法进行响应体处理
     * @param returnType the return type
     * @param converterType the selected converter type
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
       
        //判断类是否包含 EncryptDecrypt 注解
        final Class<?> containingClass = returnType.getContainingClass();
        if (containingClass.isAnnotationPresent(Encrypt.class)) {
            return  true;
        }
        //判断方法上是否包含 EncryptDecrypt 注解
        if (returnType.hasMethodAnnotation(Encrypt.class)){
            return  true;
        }
        return  false;
    }
    /**
     * 在响应体写入前对响应进行修改或增强
     * @param body the body to be written
     * @param returnType the return type of the controller method
     * @param selectedContentType the content type selected through content negotiation
     * @param selectedConverterType the converter type selected to write to the response
     * @param request the current request
     * @param response the current response
     * @return
     */
    @Override
    public ResultMessage beforeBodyWrite(ResultMessage body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        if (200 ==  body.getCode() && ObjectUtil.isNotNull(body.getResult())) {
            String encrypt = EncryptionUtils.encrypt(String.valueOf(body.getResult()));
            body.setResult(encrypt);
        }
        return body;
    };

4、 测试

1、在类上或者方法上添加@Encrypt注解
2、使用测试工具进行测试
在这里插入图片描述result就是经过加密的结果

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值