背景
为了服务阿里云交付场景,沉淀重复组件;我们现在针对身份证、姓名、电话号码等敏感字段进行加密存放,读取的时候进行解密的需求做数据库加解密组件封装。
主要功能
● 数据库指定字段加解密:配置指定Mapper里的字段,对其进行加解密。
1.examples代码获取
1.1 示例程序
📎mybatis-security-starter-example.zip
1.2 setting.xml
📎settings_public.xml
使用
如果需要使用已发布的版本,在dependencies 中添加如下依赖
<dependency>
<groupId>com.aliyun.gts.bpaas</groupId>
<artifactId>mybatis-security-interceptor-starter</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
在配置中包含如下配置
## 是否启用数据库加解密组件 true为使用,不配置或为false不启用
gts.mybatis.security.interceptor=true
## 自定义加密解密类,需要实现com.aliyun.gts.bpaas.mybatis.security.encrypt.IEncryptDecrypt接口类
## 默认为:com.aliyun.gts.bpaas.mybatis.security.encrypt.DESEncryptDecrypt
#gts.mybatis.security.encryptClass=com.aliyun.gts.bpaas.example.encrypt.DESEncryptDecrypt
## 数据库加解密字段配置文件路径(资源目录下的路径),配置文件需要是xxx.properties格式
## 如:默认的配置文件为cipher-info.properties,加解密字段配置必选添加
## 配置文件格式:key为mapper类的className,值为需要加解密的字段名称(不是数据库字段,是数据库字段对应实体类的字段名称)
## 如:com.aliyun.gts.bpaas.example.dao.UserMapper=name,phoneNo
#gts.mybatis.security.cipherInfo=test.properties
示例cipher-info.properties文件配置:
com.aliyun.gts.bpaas.example.dao.UserMapper=name,phoneNo
需要自定义加解密类,加解密类需求实现com.aliyun.gts.bpaas.mybatis.security.encrypt.IEncryptDecrypt接口类 如des加解密代码示例:
public class DESEncryptDecrypt implements IEncryptDecrypt {
/**
* 偏移变量,固定占8位字节
*/
private final static String IV_PARAMETER = "12345678";
/**
* 密钥算法
*/
private static final String ALGORITHM = "DES";
/**
* 加密/解密算法-工作模式-填充模式
*/
private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";
private static final String KEY = "liguotai";
private SecretKey secretKey;
{
try {
DESKeySpec dks = new DESKeySpec(KEY.getBytes(StandardCharsets.UTF_8));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
secretKey = keyFactory.generateSecret(dks);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public String encrypt(String str) {
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] bytes = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
return new String(Base64.getEncoder().encode(bytes));
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
@Override
public String decrypt(String str) {
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
return new String(cipher.doFinal(Base64.getDecoder()
.decode(str.getBytes(StandardCharsets.UTF_8))), StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
加解密结果如下图:
配置列表