如何优雅的实现 Spring Boot 接口参数加密解密?一篇文章带你了解

因为有小伙伴刚好问到 RequestBodyAdvice 的用法,松哥就抽空撸一篇文章和大家聊聊这个话题。

加密解密本身并不是难事,问题是在何时去处理?定义一个过滤器,将请求和响应分别拦截下来进行处理也是一个办法,这种方式虽然粗暴,但是灵活,因为可以拿到一手的请求参数和响应数据。不过 SpringMVC 中给我们提供了 ResponseBodyAdvice 和 RequestBodyAdvice,利用这两个工具可以对请求和响应进行预处理,非常方便。

所以今天这篇文章有两个目的:

  • 分享参数/响应加解密的思路。
  • 分享 ResponseBodyAdvice 和 RequestBodyAdvice 的用法。

好了,那么接下来就不废话了,我们一起来看下。

1.开发加解密 starter

为了让我们开发的这个工具更加通用,也为了复习一下自定义 Spring Boot Starter,这里我们就将这个工具做成一个 stater,以后在 Spring Boot 项目中直接引用就可以。

首先我们创建一个 Spring Boot 项目,引入 spring-boot-starter-web 依赖:

<dependency>



    <groupId>org.springframework.boot</groupId>



    <artifactId>spring-boot-starter-web</artifactId>



    <scope>provided</scope>



    <version>2.4.3</version>



</dependency>

因为我们这个工具是为 Web 项目开发的,以后必然使用在 Web 环境中,所以这里添加依赖时 scope 设置为 provided。

依赖添加完成后,我们先来定义一个加密工具类备用,加密这块有多种方案可以选择,对称加密、非对称加密,其中对称加密又可以使用 AES、DES、3DES 等不同算法,这里我们使用 Java 自带的 Cipher 来实现对称加密,使用 AES 算法:

public class AESUtils {



 



    private static final String AES_ALGORITHM = "AES/ECB/PKCS5Padding";



 



    // 获取 cipher



    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加密



    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解密



    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 算法进行编码,获取可读字符串。换言之,上面的 AES 加密方法的返回值是一个 Base64 编码之后的字符串,AES 解密方法的参数也是一个 Base64 编码之后的字符串,先对该字符串进行解码,然后再解密。

接下来我们封装一个响应工具类备用,这个大家如果经常看松哥视频已经很了解了:

public class RespBean {



    private Integer status;



    private String msg;



    private Object obj;



 



    public static RespBean build() {



        return new RespBean();



    }



 



    public static RespBean ok(String msg) {



        return new RespBean(200, msg, null);



    }



 



    public static RespBean ok(String msg, Object obj) {



        return new RespBean(200, msg, obj);



    }



 



    public static RespBean error(String msg) {



        return new RespBean(500, msg, null);



    }



 



    public static RespBean error(String msg, Object obj) {



        return new RespBean(500, msg, obj);



    }



 



    private RespBean() {



    }



 



    private RespBean(Integer status, String msg, Object obj) {



        this.status = status;



        this.msg = msg;



        this.obj = obj;



    }



 



    public Integer getStatus() {



        return status;



    }



 



    public RespBean setStatus(Integer status) {



        this.status = status;



        return this;



    }



 



    public String getMsg() {



        return msg;



    }



 



    public RespBean setMsg(String msg) {



        this.msg = msg;



        return this;



    }



 



    public Object getObj() {



        return obj;



    }



 



    public RespBean setObj(Object obj) {



        this.obj = obj;



        return this;



    }



}

接下来我们定义两个注解 @Decrypt@Encrypt

@Retention(RetentionPolicy.RUNTIME)



@Target({ElementType.METHOD,ElementType.PARAMETER})



public @interface Decrypt {



}



@Retention(RetentionPolicy.RUNTIME)



@Target(ElementType.METHOD)



public @interface Encrypt {



}

这两个注解就是两个标记,在以后使用的过程中,哪个接口方法添加了 @Encrypt 注解就对哪个接口的数据加密返回,哪个接口/参数添加了 @Decrypt 注解就对哪个接口/参数进行解密。这个定义也比较简单,没啥好说的,需要注意的是 @Decrypt@Encrypt 多了一个使用场景就是 @Decrypt 可以用在参数上。

考虑到用户可能会自己配置加密的 key,因此我们再来定义一个 EncryptProperties 类来读取用户配置的 key:

@ConfigurationProperties(prefix = "spring.encrypt")



public class EncryptProperties {



    private final static String DEFAULT_KEY = "www.itboyhub.com";



    private String key = DEFAULT_KEY;



 



    public String getKey() {



        return key;



    }



 



    public void setKey(String key) {



        this.key = key;



    }



}

这里我设置了默认的 key 是 www.itboyhub.com,key 是 16 位字符串,松哥这个网站地址刚好满足。以后如果用户想自己配置 key,只需要在 application.properties 中配置 spring.encrypt.key=xxx 即可。

所有准备工作做完了,接下来就该正式加解密了。

因为松哥这篇文章一个很重要的目的是想和大家分享 ResponseBodyAdvice 和 RequestBodyAdvice 的用法,RequestBodyAdvice 在做解密的时候倒是没啥问题,而 ResponseBodyAdvice 在做加密的时候则会有一些局限,不过影响不大,还是我前面说的,如果想非常灵活的掌控一切,那还是自定义过滤器吧。这里我就先用这两个工具来实现了。

另外还有一点需要注意,ResponseBodyAdvice 在你使用了 @ResponseBody 注解的时候才会生效,RequestBodyAdvice 在你使用了 @RequestBody 注解的时候才会生效,换言之,前后端都是 JSON 交互的时候,这两个才有用。不过一般来说接口加解密的场景也都是前后端分离的时候才可能有的事。

先来看接口加密:

@EnableConfigurationProperties(EncryptProperties.class)



@ControllerAdvice



public class EncryptResponse implements ResponseBodyAdvice<RespBean> {



    private ObjectMapper om = new ObjectMapper();



    @Autowired



    EncryptProperties encryptProperties;



    @Override



    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {



        return returnType.hasMethodAnnotation(Encrypt.class);



    }



 



    @Override



    public RespBean beforeBodyWrite(RespBean body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {



        byte[] keyBytes = encryptProperties.getKey().getBytes();



        try {



            if (body.getMsg()!=null) {



                body.setMsg(AESUtils.encrypt(body.getMsg().getBytes(),keyBytes));



            }



            if (body.getObj() != null) {



                body.setObj(AESUtils.encrypt(om.writeValueAsBytes(body.getObj()), keyBytes));



            }



        } catch (Exception e) {



            e.printStackTrace();



        }



        return body;



    }



}

我们自定义 EncryptResponse 类实现 ResponseBodyAdvice接口,泛型表示接口的返回类型,这里一共要实现两个方法:

  1. supports:这个方法用来判断什么样的接口需要加密,参数 returnType 表示返回类型,我们这里的判断逻辑就是方法是否含有 @Encrypt 注解,如果有,表示该接口需要加密处理,如果没有,表示该接口不需要加密处理。
  2. beforeBodyWrite:这个方法会在数据响应之前执行,也就是我们先对响应数据进行二次处理,处理完成后,才会转成 json 返回。我们这里的处理方式很简单,RespBean 中的 status 是状态码就不用加密了,另外两个字段重新加密后重新设置值即可。
  3. 另外需要注意,自定义的 ResponseBodyAdvice 需要用 @ControllerAdvice 注解来标记。

再来看接口解密:

@EnableConfigurationProperties(EncryptProperties.class)



@ControllerAdvice



public class DecryptRequest extends RequestBodyAdviceAdapter {



    @Autowired



    EncryptProperties encryptProperties;



    @Override



    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {



        return methodParameter.hasMethodAnnotation(Decrypt.class) || methodParameter.hasParameterAnnotation(Decrypt.class);



    }



 



    @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[] decrypt = AESUtils.decrypt(body, encryptProperties.getKey().getBytes());



            final ByteArrayInputStream bais = new ByteArrayInputStream(decrypt);



            return new HttpInputMessage() {



                @Override



                public InputStream getBody() throws IOException {



                    return bais;



                }



 



                @Override



                public HttpHeaders getHeaders() {



                    return inputMessage.getHeaders();



                }



            };



        } catch (Exception e) {



            e.printStackTrace();



        }



        return super.beforeBodyRead(inputMessage, parameter, targetType, converterType);



    }



}
  1. 首先大家注意,DecryptRequest 类我们没有直接实现 RequestBodyAdvice 接口,而是继承自 RequestBodyAdviceAdapter 类,该类是 RequestBodyAdvice 接口的子类,并且实现了接口中的一些方法,这样当我们继承自 RequestBodyAdviceAdapter 时,就只需要根据自己实际需求实现某几个方法即可。
  2. supports:该方法用来判断哪些接口需要处理接口解密,我们这里的判断逻辑是方法上或者参数上含有 @Decrypt 注解的接口,处理解密问题。
  3. beforeBodyRead:这个方法会在参数转换成具体的对象之前执行,我们先从流中加载到数据,然后对数据进行解密,解密完成后再重新构造 HttpInputMessage 对象返回。

接下来,我们再来定义一个自动化配置类,如下:

@Configuration



@ComponentScan("org.javaboy.encrypt.starter")



public class EncryptAutoConfiguration {



 



}

这个也没啥好说的,比较简单。

最后,resources 目录下定义 META-INF,然后再定义 spring.factories 文件,内容如下:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.javaboy.encrypt.starter.autoconfig.EncryptAutoConfiguration

这样当项目启动时,就会自动加载该配置类。

至此,我们的 starter 就开发完成啦。

2.打包发布

我们可以将项目安装到本地仓库,也可以发布到线上供他人使用。

2.1 安装到本地仓库

安装到本地仓库比较简单,直接 mvn install,或者在 IDEA 中,点击右边的 Maven,然后双击 install,如下:

img

2.2 发布到线上

发不到线上我们可以使用 JitPack 来做。

首先我们在 GitHub 上创建一个仓库,将我们的代码上传上去,这个过程应该不用我多说吧。

上传成功后,点击右边的 Create a new release 按钮,发布一个正式版,如下:

img

img

发布成功后,打开 jitpack,输入仓库的完整路径,点击 lookup 按钮,查找到之后,再点击 Get it 按钮完成构建,如下:

img

构建成功后,JitPack 上会给出项目引用方式:

img

注意引用时将 tag 改成你具体的版本号。

至此,我们的工具就已经成功发布了!小伙伴们可以通过如下方式引用这个 starter:

<dependencies>



    <dependency>



        <groupId>com.github.lenve</groupId>



        <artifactId>encrypt-spring-boot-starter</artifactId>



        <version>0.0.3</version>



    </dependency>



</dependencies>



<repositories>



    <repository>



        <id>jitpack.io</id>



        <url>https://jitpack.io</url>



    </repository>



</repositories>

3.应用

我们创建一个普通的 Spring Boot 项目,引入 web 依赖,再引入我们刚刚的 starter 依赖,如下:

<dependencies>



    <dependency>



        <groupId>org.springframework.boot</groupId>



        <artifactId>spring-boot-starter-web</artifactId>



    </dependency>



    <dependency>



        <groupId>com.github.lenve</groupId>



        <artifactId>encrypt-spring-boot-starter</artifactId>



        <version>0.0.3</version>



    </dependency>



    <dependency>



        <groupId>org.springframework.boot</groupId>



        <artifactId>spring-boot-starter-test</artifactId>



        <scope>test</scope>



    </dependency>



</dependencies>



<repositories>



    <repository>



        <id>jitpack.io</id>



        <url>https://jitpack.io</url>



    </repository>



</repositories>

然后再创建一个实体类备用:

public class User {



    private Long id;



    private String username;



    //省略 getter/setter



}

创建两个测试接口:

@RestController



public class HelloController {



    @GetMapping("/user")



    @Encrypt



    public RespBean getUser() {



        User user = new User();



        user.setId((long) 99);



        user.setUsername("javaboy");



        return RespBean.ok("ok", user);



    }



 



    @PostMapping("/user")



    public RespBean addUser(@RequestBody @Decrypt User user) {



        System.out.println("user = " + user);



        return RespBean.ok("ok", user);



    }



}

第一个接口使用了 @Encrypt 注解,所以会对该接口的数据进行加密(如果不使用该注解就不加密),第二个接口使用了 @Decrypt 所以会对上传的参数进行解密,注意 @Decrypt 注解既可以放在方法上也可以放在参数上。

接下来启动项目进行测试。

首先测试 get 请求接口:

img

可以看到,返回的数据已经加密。

再来测试 post 请求:

img

可以看到,参数中的加密数据已经被还原了。

如果用户想要修改加密密钥,可以在 application.properties 中添加如下配置:

spring.encrypt.key=1234567890123456

加密数据到了前端,前端也有一些 js 工具来处理加密数据,这个松哥后面有空再和大家说说 js 的加解密。

4.小结

好啦,今天这篇文章主要是想和大家聊聊 ResponseBodyAdvice 和 RequestBodyAdvice 的用法,一些加密思路,当然 ResponseBodyAdvice 和 RequestBodyAdvice 还有很多其他的使用场景,小伙伴们可以自行探索~本文使用了对称加密中的 AES 算法,大家也可以尝试改成非对称加密。

好啦,今天就聊这么多,小伙伴们可以去试试啦~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序源日志

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值