开发过程中,你是否遇到需要对DB
敏感数据进行加密,通常的做法是,存储的时候调用加密方法,查询的时候对结果进行解密,
嗯?这应该是一个痛苦的过程,好吧,今晚给大家安利一个强大的工具data-shield
,针对mybatis
架构,对数据在进行写入时加密,查询解密,为你的数据保驾护航,
我想你一定会爱上它
data-shield
data-shield
的实现采用mybatis
的Interceptor
实现,不仅实现的常规的查询和更新,也针对Cursor
模式下的查询操作,
对业务代码无任何浸入性,只需要在需要加密的字段,添加一个注解,全程帮你完成数据的加密及解密操作,真是开发一大利器,话不多说,
进入今日的正题
pom.xml配置
<dependency>
<groupId>com.github.homeant</groupId>
<artifactId>data-shield-spring-boot-starter</artifactId>
<version>1.0-RELEASE</version>
</dependency>
yaml配置
app:
data:
shield:
enable: true
strategy: aes #支持AES/DES模式
key: AD42F6697B035B7580E4FEF93BE20BAD
业务字段配置
为需要处理的业务字段添加@TableField注解,只支持String类型
encrypt: 修改过程是否需要加密,默认为false
decode: 查询过程是否需要解密,默认为false
asserts: decode为true时,针对某些数据(历史数据)提供断言,默认值DefaultAssert.class(encrypt=true,decode=true)
@Data
public class User {
private Integer id;
private String username;
@TableField(encrypt = true,decode = true,assertion=Base64Assert.class)
private String phone;
}
代码调用
public class Test{
@Autowired
private UserMapper userMapper;
@Autowired
private SqlSessionFactory sqlSessionFactory;
/**
* RSA 加密模式会导致密文过长,不推荐使用
*/
@Test
public void test() {
User user = new User();
user.setUsername("tom");
user.setPassword("p@ssw0rd1234567");
userMapper.insert(user);
DataShieldHelper.dataMasking();
Optional<User> optional = userMapper.selectOn(user.getId());
DataShieldHelper.clearDataMasking();
optional.ifPresent(r -> {
log.debug("user:{}", r);
});
}
@Test
public void cursorTest() throws IOException {
try (SqlSession sqlSession = sqlSessionFactory.openSession();
Cursor<User> userCursor = sqlSession.getMapper(UserMapper.class).selectList()) {
Iterator<User> iterator = userCursor.iterator();
while (iterator.hasNext()){
log.info("user:{}",iterator.next());
}
}
}
}
2021-04-03 16:23:16.604 DEBUG 3020 --- [ main] c.g.h.d.shield.mapper.UserMapper.insert : ==> Preparing: insert into t_user (username,password) values ( ?, ?)
2021-04-03 16:23:16.629 DEBUG 3020 --- [ main] c.g.h.d.shield.mapper.UserMapper.insert : ==> Parameters: tom(String), L0wfhbKDAELRnj03GtjKoQ==(String)
2021-04-03 16:23:16.651 DEBUG 3020 --- [ main] c.g.h.d.shield.mapper.UserMapper.insert : <== Updates: 1
2021-04-03 16:23:16.675 DEBUG 3020 --- [ main] c.g.h.d.s.mapper.UserMapper.selectOn : ==> Preparing: select id,username,password from t_user where id = ?
2021-04-03 16:23:16.675 DEBUG 3020 --- [ main] c.g.h.d.s.mapper.UserMapper.selectOn : ==> Parameters: 75(Integer)
2021-04-03 16:23:23.313 DEBUG 3020 --- [ main] c.g.h.d.s.mapper.UserMapper.selectOn : <== Total: 1
2021-04-03 16:23:26.166 DEBUG 3020 --- [ main] com.github.homeant.data.shield.DataTest : user:User(id=75, username=tom, password=p@ssw0rd1234567)
mysql> select * from t_user;
+----+----------+--------------------------+
| id | username | password |
+----+----------+--------------------------+
| 74 | tom | L0wfhbKDAELRnj03GtjKoQ== |
| 75 | tom | L0wfhbKDAELRnj03GtjKoQ== |
+----+----------+--------------------------+
2 rows in set (0.03 sec)