Skip to content

API 加密

简介

continew-starter-encrypt-api 是 ContiNew Starter 加密模块提供的 API 接口报文加解密能力(@since 2.14.0),采用 RSA + AES 混合信封加密,通过 Servlet 过滤器自动解密请求体、加密响应体,防止接口报文明文传输被窃取。

主要特性

  • 信封加密: AES 加密报文 + RSA 加密 AES 密钥,兼顾性能与安全
  • 自动生效: 基于 Servlet 过滤器处理,请求解密无需业务代码参与
  • 注解控制: @ApiEncrypt 注解控制响应是否加密
  • 跨域友好: 自动通过 Access-Control-Expose-Headers 暴露加密头

快速开始

引入依赖

pom.xml
xml
<dependency>
    <groupId>top.continew.starter</groupId>
    <artifactId>continew-starter-encrypt-api</artifactId>
</dependency>

添加配置

配置详情请查看:top.continew.starter.encrypt.api.autoconfigure.ApiEncryptProperties@since 2.14.0)。

application.yml
yaml
--- ### API 加密配置
continew-starter.encrypt:
  api:
    # 是否启用(默认 true)
    enabled: true
    # 请求头中 AES 密钥键名(默认 X-Api-Encrypt)
    secret-key-header: X-Api-Encrypt
    # 响应加密公钥
    public-key: ''
    # 请求解密私钥
    private-key: ''

使用 @ApiEncrypt 注解

在 Controller 方法上标注 @ApiEncrypt 注解(@since 2.14.0,属性 response 默认 true 表示加密响应):

java
@Operation(summary = "新增数据")
@ApiEncrypt
@PostMapping
public RespBody<Void> add(@RequestBody @Valid DemoReq req) {
    // 请求体已由过滤器自动解密,响应体将自动加密
}

请求/响应处理流程

过滤器注册于 /*(最高优先级,仅处理 POST/PUT 请求):

  1. 请求解密:请求头携带 X-Api-Encrypt(经 RSA 公钥加密后 Base64 编码的 AES 密钥)时,使用 RSA 私钥解出 AES 密钥,再解密请求体;
  2. 响应加密:命中 @ApiEncrypt(response = true) 的接口,随机生成 AES 密钥加密响应体,并将 RSA 公钥加密后的 AES 密钥 Base64 编码写入响应头 X-Api-Encrypt

客户端按相同约定实现:请求时将 AES 密钥 Base64 后用 RSA 公钥加密放入请求头;响应时从响应头取出 AES 密钥并解密响应体。

核心依赖

依赖描述
top.continew.starter:continew-starter-encrypt-core加密模块 - 核心模块(IEncryptor SPI、算法枚举)

参考资料

  1. ContiNew Starter 字段加密