前言
对于大多数系统来说,敏感数据的加密存储都是必须考虑和实现的。最近在公司的项目中也接到了相关的安全需求,因为项目使用了 mybatis 作为数据库持久层框架,在经过一番调研后决定使用其插件机制来实现字段加解密功能,并且封装成一个轻量级、支持配置、方便扩展的组件提供给其他项目使用。
mybatis 的插件机制
简介
mybatis 提供了插件功能,它允许你拦截 mybatis 执行过程中的某个方法,对其增加自定义操作。默认情况下,mybatis 允许拦截的方法包括:
| 类 | 方法 | 说明 |
|---|---|---|
| org.apache.ibatis.executor.executor | update, query, flushstatements, commit, rollback, gettransaction, close, isclosed | 拦截执行器的方法 |
| org.apache.ibatis.executor.parameter.parameterhandler | getparameterobject, setparameters | 说明:拦截参数处理的方法 |
| org.apache.ibatis.executor.resultset.resultsethandler | handleresultsets, handleoutputparameters | 拦截结果集处理的方法 |
| org.apache.ibatis.executor.statement.statementhandler | prepare, parameterize, batch, update, query | 拦截 sql 语句构建的方法 |
插件实现
在 mybatis 中,一个插件其实就是一个拦截器,插件的实现方式非常简单,只需要实现 org.apache.ibatis.plugin.interceptor 接口,并且通过 @intercepts 注解指定要拦截的方法签名即可。 以下是官方文档提供的例子:
// exampleplugin.java
@intercepts({@signature(
type= executor.class,
method = "update",
args = {mappedstatement.class,object.class})})
public class exampleplugin implements interceptor {
private properties properties = new properties();
@override
public object intercept(invocation invocation) throws throwable {
// implement pre-processing if needed
object returnobject = invocation.proceed();
// implement post-processing if needed
return returnobject;
}
@override
public void setproperties(properties properties) {
this.properties = properties;
}
}
上面的插件会拦截 org.apache.ibatis.executor.executor#update 方法的所有调用,你可以在 invocation.proceed() 前后增加插件逻辑。
字段加解密实现
对于字段加解密来说,需要关注的点就是查询、插入和更新,在进行这些操作的时候需要对字段进行处理(插入、更新时加密,查询时解密),与上文提到的拦截点的对应关系如下:
- 插入、更新:
org.apache.ibatis.executor.executor#update - 查询:
org.apache.ibatis.executor.resultset.resultsethandler#handleresultsets
代码实现
先上完整代码:github.com/whitedg/myb…
一般场景下只有包含敏感数据的字段才需要进行加解密,所以需要一个注解来标记哪些字段需要加解密,这里定义为 @encryptedfield,提供两个属性:
- key:加解密时用到的密钥
- encryptor:指定加解密器,不指定则使用全局的加解密器
@documented
@inherited
@target({elementtype.field})
@retention(retentionpolicy.runtime)
public @interface encryptedfield {
string key() default "";
class<? extends iencryptor> encryptor() default iencryptor.class;
}
加密的整体思路就是通过 invocation 拿到方法参数,有两种情况:一种是实体类,一种是 parammap,实体类通过注解确定需要加密的字段,parammap 通过配置的参数名前缀确定需要加密的字段,然后使用加密器对需要加密的字段进行加密覆盖掉原始值即可。如果是实体类则在方法执行完成后还需要对 key 字段进行回写处理。 在对参数进行处理前使用 kryo 拷贝了一份源数据,目的是保留方法调用时的原始参数,避免经过插件的 sql 执行完成后,原始参数变成已加密的。
@override
public object intercept(invocation invocation) throws throwable {
object[] args = invocation.getargs();
mappedstatement ms = (mappedstatement) args[0];
object parameter = args[1];
if (util.encryptionrequired(parameter, ms.getsqlcommandtype())) {
kryo kryo = null;
try {
kryo = kryopool.obtain();
object copiedparameter = kryo.copy(parameter);
boolean isparammap = parameter instanceof mappermethod.parammap;
if (isparammap) {
//noinspection unchecked
mappermethod.parammap<object> parammap = (mappermethod.parammap<object>) copiedparameter;
encryptparammap(parammap);
} else {
encryptentity(copiedparameter);
}
args[1] = copiedparameter;
object result = invocation.proceed();
if (!isparammap) {
handlekeyproperties(ms, parameter, copiedparameter);
}
return result;
} finally {
if (kryo != null) {
kryopool.free(kryo);
}
}
} else {
return invocation.proceed();
}
}
解密插件与加密插件类似,通过 invocation 拿到查询 sql 执行后返回的结果集,有两种情况:一种是返回 arraylist,一种是返回单个实体,同样通过注解确定需要解密的字段对其进行解密然后覆盖掉原始加密的值。
@override
public object intercept(invocation invocation) throws throwable {
object result = invocation.proceed();
if (result == null) {
return null;
}
if (result instanceof arraylist) {
//noinspection rawtypes
arraylist resultlist = (arraylist) result;
if (resultlist.isempty()) {
return result;
}
object firstitem = resultlist.get(0);
boolean needtodecrypt = util.decryptionrequired(firstitem);
if (!needtodecrypt) {
return result;
}
set<field> encryptedfields = encryptedfieldsprovider.get(firstitem.getclass());
if (encryptedfields == null || encryptedfields.isempty()) {
return result;
}
for (object item : resultlist) {
decryptentity(encryptedfields, item);
}
} else {
if (util.decryptionrequired(result)) {
decryptentity(encryptedfieldsprovider.get(result.getclass()), result);
}
}
return result;
}
支持配置、方便扩展的实现
作为一个通用的组件(这里命名为 mybatis-crypto),支持配置和方便扩展是基本的要求。
mybatis-crypto 提供了以下几个配置项满足基本使用:
| 配置项 | 说明 | 默认值 |
|---|---|---|
| mybatis-crypto.enabled | 是否启用 mybatis-crypto | true |
| mybatis-crypto.fail-fast | 快速失败,加解密过程中发生异常是否中断。true:抛出异常,false:使用原始值,打印 warn 级别日志 | true |
| mybatis-crypto.mapped-key-prefixes | @param 参数名的前缀,前缀匹配则会进行加密处理 | 空 |
| mybatis-crypto.default-encryptor | 全局默认 encryptor | 空 |
| mybatis-crypto.default-key | 全局默认 encryptor 的密钥 | 空 |
mybatis-crypto 核心包默认不提供具体的加解密方法,开发者可以通过引入 mybatis-crypto-encryptors 使用其提供的常用加解密类,或者实现 io.github.whitedg.mybatis.crypto.iencryptor 自行扩展加解密方法。
starter 封装
目前大多数项目都是基于 spring-boot 进行开发的,所以将 mybatis-crypto 封装成一个 starter 会更方便开发者使用。starter 的主要工作就是读取配置,自动装配,因此它的实现非常简单,只有两个类,mybatiscryptoproperties 获取配置,mybatiscryptoautoconfiguration 加载插件。
@configuration
@conditionalonproperty(value = "mybatis-crypto.enabled", havingvalue = "true", matchifmissing = true)
@enableconfigurationproperties(mybatiscryptoproperties.class)
public class mybatiscryptoautoconfiguration {
@bean
@conditionalonmissingbean(mybatisencryptionplugin.class)
public mybatisencryptionplugin encryptioninterceptor(mybatiscryptoproperties properties) {
return new mybatisencryptionplugin(properties.tomybatiscryptoconfig());
}
@bean
@conditionalonmissingbean(mybatisdecryptionplugin.class)
public mybatisdecryptionplugin decryptioninterceptor(mybatiscryptoproperties properties) {
return new mybatisdecryptionplugin(properties.tomybatiscryptoconfig());
}
}
总结
本文简单介绍了基于 mybatis 插件机制实现字段加解密的思路及流程,并将其封装成一个通用的 spring-boot-starter 组件,开发者可以方便的引入使用,同时也提供了加解密方法集合 mybatis-crypto-encryptors。
组件的具体使用方法和示https://github.com/whitedg/mybatis-crypto
到此这篇关于基于mybatis插件实现字段加解密的实现示例的文章就介绍到这了,更多相关mybatis 字段加解密内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论