springboot中request和response的加解密实现代码

 更新时间:2022年06月08日 08:28:07   作者:ldcaws  
这篇文章主要介绍了springboot中request和response的加解密实现,在springboot中提供了RequestBodyAdviceAdapter和ResponseBodyAdvice,利用这两个工具可以非常方便的对请求和响应进行预处理,需要的朋友可以参考下

在系统开发中,需要对请求和响应分别拦截下来进行解密和加密处理,在springboot中提供了RequestBodyAdviceAdapter和ResponseBodyAdvice,利用这两个工具可以非常方便的对请求和响应进行预处理。

1、新建一个springboot工程,pom依赖如下

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

2、自定义加密、解密的注解

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

其中加密注解放在方法上,解密注解可以放在方法上,也可以放在参数上。

3、加密算法

定义一个加密工具类,加密算法分为对称加密和非对称加密,本次使用java自带的Ciphor来实现对称加密,使用AES算法,如下

public class AESUtils {
    private static final String AES_ALGORITHM = "AES/ECB/PKCS5Padding";
    private static final String key = "1234567890abcdef";
    /**
     * 获取 cipher
     * @param key
     * @param model
     * @return
     * @throws Exception
     */
    private static Cipher getCipher(byte[] key, int model) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        cipher.init(model, secretKeySpec);
        return cipher;
    }
    /**
     * AES加密
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static String encrypt(byte[] data, byte[] key) throws Exception {
        Cipher cipher = getCipher(key, Cipher.ENCRYPT_MODE);
        return Base64.getEncoder().encodeToString(cipher.doFinal(data));
    }
    /**
     * AES解密
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        Cipher cipher = getCipher(key, Cipher.DECRYPT_MODE);
        return cipher.doFinal(Base64.getDecoder().decode(data));
    }
}

其中加密后的数据使用Base64算法进行编码,获取可读字符串;解密的输入也是一个Base64编码之后的字符串,先进行解码再进行解密。

4、对请求数据进行解密处理

@EnableConfigurationProperties(KeyProperties.class)
@ControllerAdvice
public class DecryptRequest extends RequestBodyAdviceAdapter {

    @Autowired
    private KeyProperties keyProperties;

    /**
     * 该方法用于判断当前请求,是否要执行beforeBodyRead方法
     *
     * @param methodParameter handler方法的参数对象
     * @param targetType      handler方法的参数类型
     * @param converterType   将会使用到的Http消息转换器类类型
     * @return 返回true则会执行beforeBodyRead
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return methodParameter.hasMethodAnnotation(Decrypt.class) || methodParameter.hasParameterAnnotation(Decrypt.class);
    }

    /**
     * 在Http消息转换器执转换,之前执行
     * @param inputMessage
     * @param parameter
     * @param targetType
     * @param converterType
     * @return 返回 一个自定义的HttpInputMessage
     * @throws IOException
     */
    @Override
    public HttpInputMessage beforeBodyRead(final HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        byte[] body = new byte[inputMessage.getBody().available()];
        inputMessage.getBody().read(body);
        try {
            byte[] keyBytes = keyProperties.getKey().getBytes();
            byte[] decrypt = AESUtils.decrypt(body, keyBytes);
            final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decrypt);
            return new HttpInputMessage() {
                @Override
                public InputStream getBody() throws IOException {
                    return byteArrayInputStream;
                }

                @Override
                public HttpHeaders getHeaders() {
                    return inputMessage.getHeaders();
                }
            };
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.beforeBodyRead(inputMessage, parameter, targetType, converterType);
    }
}

5、对响应数据进行加密处理

@EnableConfigurationProperties(KeyProperties.class)
@ControllerAdvice
public class EncryptResponse implements ResponseBodyAdvice<RespBean> {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private KeyProperties keyProperties;

    /**
     * 该方法用于判断当前请求的返回值,是否要执行beforeBodyWrite方法
     *
     * @param methodParameter handler方法的参数对象
     * @param converterType   将会使用到的Http消息转换器类类型
     * @return 返回true则会执行beforeBodyWrite
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
        return methodParameter.hasMethodAnnotation(Encrypt.class);
    }

    /**
     * 在Http消息转换器执转换,之前执行
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return 返回 一个自定义的HttpInputMessage,可以为null,表示没有任何响应
     */
    @Override
    public RespBean beforeBodyWrite(RespBean body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        byte[] keyBytes = keyProperties.getKey().getBytes();
        try {
            if (body.getMsg() != null) {
                body.setMsg(AESUtils.encrypt(body.getMsg().getBytes(), keyBytes));
            }
            if (body.getObj() != null) {
                body.setObj(AESUtils.encrypt(objectMapper.writeValueAsBytes(body.getObj()), keyBytes));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return body;
    }
}

6、加解密的key的配置类,从配置文件中读取

@ConfigurationProperties(prefix = "spring.encrypt")
public class KeyProperties {

    private final static String DEFAULT_KEY = "1234567890abcdef";
    private String key = DEFAULT_KEY;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }
}

7、测试

application中的key配置

spring.encrypt.key=1234567890abcdef
	@GetMapping("/user")
    @Encrypt
    public RespBean getUser() {
        User user = new User();
        user.setId(1L);
        user.setUsername("caocao");
        return RespBean.ok("ok", user);
    }

    @PostMapping("/user")
    public RespBean addUser(@RequestBody @Decrypt User user) {
        System.out.println("user = " + user);
        return RespBean.ok("ok", user);
    }

测试结果

在这里插入图片描述

在这里插入图片描述

其中get请求的接口使用了@Encrypt注解,对响应数据进行了加密处理;post请求的接口使用了@Decrypt注解作用在参数上,对请求数据进行了解密处理。

到此这篇关于springboot中request和response的加解密实现的文章就介绍到这了,更多相关springboot加解密内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot中的@ResponseStatus注解处理异常状态码

    SpringBoot中的@ResponseStatus注解处理异常状态码

    这篇文章主要介绍了SpringBoot中的@ResponseStatus注解处理异常状态码,在 SpringBoot 应用程序中,异常处理是一个非常重要的话题。当应用程序出现异常时,我们需要对异常进行处理,以保证应用程序的稳定性和可靠性,需要的朋友可以参考下
    2023-08-08
  • Springboot整合多数据源代码示例详解

    Springboot整合多数据源代码示例详解

    这篇文章主要介绍了Springboot整合多数据源代码示例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-08-08
  • springboot中如何使用openfeign进行接口调用

    springboot中如何使用openfeign进行接口调用

    这篇文章主要介绍了springboot中如何使用openfeign进行接口调用问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07
  • springboot利用easypoi实现简单导出功能

    springboot利用easypoi实现简单导出功能

    本文介绍了如何使用Spring Boot和EasyPoi库实现Excel文件的导出功能,EasyPoi是一个简化Excel和Word操作的工具,通过简单的配置和代码,可以轻松地将Java对象导出为Excel文件,并且支持图片导出等功能,感兴趣的朋友一起看看吧
    2024-12-12
  • 关于实体类中Date属性格式化@JsonFormat @DateTimeFormat

    关于实体类中Date属性格式化@JsonFormat @DateTimeFormat

    这篇文章主要介绍了关于实体类中Date属性格式化@JsonFormat @DateTimeFormat问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07
  • 解析Spring中@Controller@Service等线程安全问题

    解析Spring中@Controller@Service等线程安全问题

    这篇文章主要为大家介绍解析了Spring中@Controller@Service等线程的安全问题,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-03-03
  • Java与MySQL导致的时间不一致问题分析

    Java与MySQL导致的时间不一致问题分析

    在使用MySQL的过程中,你可能会遇到时区相关问题,本文主要介绍了Java与MySQL导致的时间不一致问题分析,具有一定的参考价值,感兴趣的可以了解一下
    2024-07-07
  • java常用工具类 IP、File文件工具类

    java常用工具类 IP、File文件工具类

    这篇文章主要为大家详细介绍了java常用工具类,包括IP、File文件工具类,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-05-05
  • Java字符串去除特殊字符内容的实例

    Java字符串去除特殊字符内容的实例

    下面小编就为大家分享一篇Java字符串去除特殊字符内容的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2017-12-12
  • Java-JFrame-swing嵌套浏览器的具体步骤

    Java-JFrame-swing嵌套浏览器的具体步骤

    下面小编就为大家带来一篇Java-JFrame-swing嵌套浏览器的具体步骤。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10

最新评论