一个注解实现 MyBatis 字段加解密

7,894 阅读1分钟

简介

mybatis-crypto 是一个基于 mybatis 插件机制实现的字段加解密组件,通过一个注解即可对敏感数据进行加解密处理。 支持自定义 Encryptor、特殊字段单独指定 Encryptorkey ,满足大部分使用场景。

模块

mybatis-crypto 包括三个模块:

  • mybatis-crypto-core 插件的核心功能模块
  • mybatis-crypto-spring-boot-starter 提供了 Spring boot 快速整合功能
  • mybatis-crypto-encryptors 提供了一些 IEncryptor 实现

使用方法

  1. 引入依赖
<dependency>
    <groupId>io.github.whitedg</groupId>
    <artifactId>mybatis-crypto-spring-boot-starter</artifactId>
    <version>${latest.version}</version>
</dependency>
  1. 实现 IEncryptor
import io.github.whitedg.mybatis.crypto.IEncryptor;

public class MyEncryptor implements IEncryptor {

    @Override
    public String encrypt(Object val2bEncrypted, String key) throws Exception {
        // 实现这个方法返回加密后的数据
        return "encrypted string";
    }

    @Override
    public String decrypt(Object val2bDecrypted, String key) throws Exception {
        // 实现这个方法返回解密后的数据
        return "decrypted string";
    }
}

或者引入 mybatis-crypto-encryptors


<dependency>
    <groupId>io.github.whitedg</groupId>
    <artifactId>mybatis-crypto-encryptors</artifactId>
    <version>${latest.version}</version>
</dependency>

使用其提供的 Encryptor

  • io.github.whitedg.mybatis.crypto.Base64Encryptor
  • io.github.whitedg.mybatis.crypto.BasicTextEncryptor
  • io.github.whitedg.mybatis.crypto.AES256Encryptor
  • io.github.whitedg.mybatis.crypto.StrongTextEncryptor
  1. 添加配置
mybatis-crypto:
  # 是否启用插件,默认 true
  enabled: true
  # 快速失败,默认 true
  fail-fast: false
  # 全局默认 Encryptor
  default-encryptor: io.github.whitedg.mybatis.crypto.BasicTextEncryptor
  # Encryptor 默认密钥
  default-key: global-key
  # mybatis @Param 注解下需要加解密的参数 key 前缀
  mapped-key-prefixes: et,encrypted
  1. 指定加密字段
  • 在需要加解密的字段上添加注解 @EncryptedField
public class User {
    @EncryptedField
    private String encryptedStr;

    @EncryptedField(encryptor = YourEncryptor.class, key = "Your Key")
    private String customizedStr;
}
  • 使用配置的 @Param 参数 key 前缀
import org.apache.ibatis.annotations.Param;

interface YourEntityMapper {
    int insert(@Param("et") YourEntity entity);

    // 支持数组
    int batchInsert(@Param("encrypted-entities") List<YourEntity> entity);

    // 返回值也支持单个对象或数组
    YourEntity selectOne();

    List<YourEntity> selectList();
}

Demo

配置项说明

配置项说明默认值
mybatis-crypto.enabled是否启用 mybatis-cryptotrue
mybatis-crypto.fail-fast快速失败,加解密过程中发生异常是否中断。true:抛出异常,false:使用原始值,打印 warn 级别日志true
mybatis-crypto.mapped-key-prefixes@Param 参数名的前缀,前缀匹配则会进行加密处理
mybatis-crypto.default-encryptor全局默认 Encryptor
mybatis-crypto.default-key全局默认 Encryptor 的密钥

开源链接

github.com/WhiteDG/myb…

实现原理

juejin.cn/post/711865…