作者:vivo 互联网服务器团队- Li Gang

本篇文章介绍应用MyBatis插件来实现数据库字段加解密的过程。

一、需要背景

公司出于平安合规的思考,须要对明文存储在数据库中的局部字段进行加密,避免未经受权的拜访以及个人信息透露。

因为我的项目已进行迭代,革新的老本太大,因而咱们选用了MyBatis插件来实现数据库加解密,保障往数据库写入数据时能对指定字段加密,读取数据时能对指定字段解密。

二、思路解析

2.1 零碎架构

  1. 对每个须要加密的字段新增密文字段(对业务有侵入),批改数据库、mapper.xml以及DO对象,通过插件的形式把针对明文/密文字段的加解密进行收口。
  2. 自定义Executor对SELECT/UPDATE/INSERT/DELETE等操作的明文字段进行加密并设置到密文字段。
  3. 自定义插件ResultSetHandler负责针对查问后果进行解密,负责对SELECT等操作的密文字段进行解密并设置到明文字段。

2.2 零碎流程

  1. 新增加解密流程管制开关,别离管制写入时是只写原字段/双写/只写加密后的字段,以及读取时是读原字段还是加密后的字段。
  2. 新增历史数据加密工作,对历史数据批量进行加密,写入到加密后字段。
  3. 出于平安上的思考,流程里还会有一些校验/弥补的工作,这里不再赘述。

三、计划制订

3.1 MyBatis插件简介

MyBatis 预留了 org.apache.ibatis.plugin.Interceptor 接口,通过实现该接口,咱们能对MyBatis的执行流程进行拦挡,接口的定义如下:

public interface Interceptor {  Object intercept(Invocation invocation) throws Throwable;  Object plugin(Object target);  void setProperties(Properties properties);}

其中有三个办法:

  • 【intercept】:插件执行的具体流程,传入的Invocation是MyBatis对被代理的办法的封装。
  • 【plugin】:应用以后的Interceptor创立代理,通常的实现都是 Plugin.wrap(target, this),wrap办法内应用 jdk 创立动静代理对象。
  • 【setProperties】:参考下方代码,在MyBatis配置文件中配置插件时能够设置参数,在setProperties函数中调用 Properties.getProperty("param1") 办法能够失去配置的值。
<plugins>    <plugin interceptor="com.xx.xx.xxxInterceptor">        <property name="param1" value="value1"/>    </plugin></plugins>

在实现intercept函数对MyBatis的执行流程进行拦挡前,咱们须要应用@Intercepts注解指定拦挡的办法。

@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }),        @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }) })

参考上方代码,咱们能够指定须要拦挡的类和办法。当然咱们不能对任意的对象做拦挡,MyBatis件可拦挡的类为以下四个。

  1. Executor
  2. StatementHandler
  3. ParameterHandler
  4. ResultSetHandler

回到数据库加密的需要,咱们须要从下面四个类里抉择能用来实现入加入密和出参解密的类。在介绍这四个类之前,须要对MyBatis的执行流程有肯定的理解。

3.2 Spring-MyBatis执行流程

(1)Spring通过sqlSessionFactoryBean创立sqlSessionFactory,在应用sqlSessionFactoryBean时,咱们通常会指定configLocation和mapperLocations,来通知sqlSessionFactoryBean去哪里读取配置文件以及去哪里读取mapper文件。

(2)失去配置文件和mapper文件的地位后,别离调用XmlConfigBuilder.parse()和XmlMapperBuilder.parse()创立Configuration和MappedStatement,Configuration类顾名思义,寄存的是MyBatis所有的配置,而MappedStatement类寄存的是每条SQL语句的封装,MappedStatement以map的模式寄存到Configuration对象中,key为对应办法的全门路。

(3)Spring通过ClassPathMapperScanner扫描所有的Mapper接口,为其创立BeanDefinition对象,但因为他们实质上都是没有被实现的接口,所以Spring会将他们的BeanDefinition的beanClass属性批改为MapperFactorybean。

(4)MapperFactoryBean也实现了FactoryBean接口,Spring在创立Bean时会调用FactoryBean.getObject()办法获取Bean,最终是通过mapperProxyFactory的newInstance办法为mapper接口创立代理,创立代理的形式是JDK,最终生成的代理对象是MapperProxy。

(5)调用mapper的所有接口实质上调用的都是MapperProxy.invoke办法,外部调用sqlSession的insert/update/delete等各种办法。

MapperMethod.javapublic Object execute(SqlSession sqlSession, Object[] args) {  Object result;  if (SqlCommandType.INSERT == command.getType()) {    Object param = method.convertArgsToSqlCommandParam(args);    result = rowCountResult(sqlSession.insert(command.getName(), param));  } else if (SqlCommandType.UPDATE == command.getType()) {    Object param = method.convertArgsToSqlCommandParam(args);    result = rowCountResult(sqlSession.update(command.getName(), param));  } else if (SqlCommandType.DELETE == command.getType()) {    Object param = method.convertArgsToSqlCommandParam(args);    result = rowCountResult(sqlSession.delete(command.getName(), param));  } else if (SqlCommandType.SELECT == command.getType()) {    if (method.returnsVoid() && method.hasResultHandler()) {      executeWithResultHandler(sqlSession, args);      result = null;    } else if (method.returnsMany()) {      result = executeForMany(sqlSession, args);    } else if (method.returnsMap()) {      result = executeForMap(sqlSession, args);    } else {      Object param = method.convertArgsToSqlCommandParam(args);      result = sqlSession.selectOne(command.getName(), param);    }  } else if (SqlCommandType.FLUSH == command.getType()) {      result = sqlSession.flushStatements();  } else {    throw new BindingException("Unknown execution method for: " + command.getName());  }  if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {    throw new BindingException("Mapper method '" + command.getName()        + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");  }  return result;}

(6)SqlSession能够了解为一次会话,SqlSession会从Configuration中获取对应MappedStatement,交给Executor执行。

DefaultSqlSession.java@Overridepublic <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {  try {    // 从configuration对象中应用被调用办法的全门路,获取对应的MappedStatement    MappedStatement ms = configuration.getMappedStatement(statement);    return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);  } catch (Exception e) {    throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);  } finally {    ErrorContext.instance().reset();  }}

(7)Executor会先创立StatementHandler,StatementHandler能够了解为是一次语句的执行。

(8)而后Executor会获取连贯,具体获取连贯的形式取决于Datasource的实现,能够应用连接池等形式获取连贯。

(9)之后调用StatementHandler.prepare办法,对应到JDBC执行流程中的Connection.prepareStatement这一步。

(10)Executor再调用StatementHandler的parameterize办法,设置参数,对应到JDBC执行流程的StatementHandler.setXXX()设置参数,外部会创立ParameterHandler办法。

SimpleExecutor.java@Overridepublic <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {  Statement stmt = null;  try {    Configuration configuration = ms.getConfiguration();    // 创立StatementHandler,对应第7步    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);    // 获取连贯,再调用conncetion.prepareStatement创立prepareStatement,设置参数    stmt = prepareStatement(handler, ms.getStatementLog());    // 执行prepareStatement    return handler.<E>query(stmt, resultHandler);  } finally {    closeStatement(stmt);  }}

(11)再由ResultSetHandler解决返回后果,解决JDBC的返回值,将其转换为Java的对象。

3.3 MyBatis插件的创立机会

在Configuration类中,咱们能看到newExecutor、newStatementHandler、newParameterHandler、newResultSetHandler这四个办法,插件的代理类就是在这四个办法中创立的,我以StatementHandeler的创立为例:

Configuration.javapublic StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {  StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);  // 应用责任链的模式创立代理  statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);  return statementHandler;} InterceptorChain.javapublic Object pluginAll(Object target) {  for (Interceptor interceptor : interceptors) {    target = interceptor.plugin(target);  }  return target;}

interceptor.plugin对应到咱们本人实现的interceptor里的办法,通常的实现是 Plugin.wrap(target, this); ,该办法外部创立代理的形式为JDK。

3.4 MyBatis插件可拦挡类抉择

Mybatis实质上是对JDBC执行流程的封装。联合上图咱们简要概括下Mybatis这几个可被代理类的职能。

  • 【Executor】: 真正执行SQL语句的对象,调用sqlSession的办法时,实质上都是调用executor的办法,还负责获取connection,创立StatementHandler。
  • 【StatementHandler】: 创立并持有ParameterHandler和ResultSetHandler对象,操作JDBC的statement与进行数据库操作。
  • 【ParameterHandler】: 解决入参,将Java办法上的参数设置到被执行语句中。
  • 【ResultSetHandler】: 解决SQL语句的执行后果,将返回值转换为Java对象。

对于入参的加密,咱们须要在ParameterHandler调用prepareStatement.setXXX()办法设置参数前,将参数值批改为加密后的参数,这样一看如同拦挡Executor/StatementHandler/ParameterHandler都能够。

但实际上呢?因为咱们的并不是在原始字段上做加密,而是新增了一个加密后字段,这会带来什么问题?请看上面这条mapper.xml文件中加了加密后字段的动静SQL:

<select id="selectUserList" resultMap="BaseResultMap" parameterType="com.xxx.internet.demo.entity.UserInfo">        SELECT        *        FROM        `t_user_info`        <where>            <if test="phone != null">                `phone` = #{phone}            </if><!--            明文字段-->            <if test="secret != null">                AND `secret` = #{secret}            </if><!--            加密后字段-->            <if test="secretCiper != null">                AND `secret_ciper` = #{secretCiper}            </if>            <if test="name">                AND `name` = #{name}            </if>        </where>        ORDER BY `update_time` DESC    </select>

能够看到这条语句带了动静标签,那必定不能间接交给JDBC创立prepareStatement,须要先将其解析成动态SQL,而这一步是在Executor在调用StatementHandler.parameterize()前做的,由MappedStatementHandler.getBoundSql(Object parameterObject)函数解析动静标签,生成动态SQL语句,这里的parameterObject咱们能够临时先将其看成一个Map,键值别离为参数名和参数值。

那么咱们来看下用StatementHandler和ParameterHandler做参数加密会有什么问题,在执行MappedStatementHandler.getBoundSql时,parameterObject中并没有写入加密后的参数,在判断标签时必然为否,最初生成的动态SQL必然不蕴含加密后的字段,后续不论咱们在StatementHandler和ParameterHandler中怎么解决parameterObject,都无奈实现入参的加密。

因而,在入参的加密上咱们只能抉择拦挡Executor的update和query办法。

那么返回值的解密呢?参考流程图,咱们能对ResultSetHandler和Executor做拦挡,事实也的确如此,在解决返回值这一点上,这两者是等价的,ResultSetHandler.handleResultSet()的返回值间接透传给Executor,再由Executor透传给SqlSession,所以两者任选其一就能够。

四、计划施行

在晓得须要拦挡的对象后,就能够开始实现加解密插件了。首先定义一个办法维度的注解。

/** * 通过注解来表明,咱们须要对那个字段进行加密 */@Target({ ElementType.METHOD })@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface TEncrypt {    /**     * 加密时从srcKey到destKey     * @return     */    String[] srcKey() default {};     /**     * 解密时从destKey到srcKey     * @return     */    String[] destKey() default {};}

将该注解打在须要加解密的DAO层办法上。

UserMapper.javapublic interface UserMapper {    @TEncrypt(srcKey = {"secret"}, destKey = {"secretCiper"})    List<UserInfo> selectUserList(UserInfo userInfo);    }

批改xxxMapper.xml文件

<mapper namespace="com.xxx.internet.demo.mapper.UserMapper">    <resultMap id="BaseResultMap" type="com.xxx.internet.demo.entity.UserInfo">        <id column="id" jdbcType="BIGINT" property="id" />        <id column="phone" jdbcType="VARCHAR" property="phone"/>        <id column="secret" jdbcType="VARCHAR" property="secret"/><!--        加密后映射-->        <id column="secret_ciper" jdbcType="VARCHAR" property="secretCiper"/>        <id column="name" jdbcType="VARCHAR" property="name" />    </resultMap>     <select id="selectUserList" resultMap="BaseResultMap" parameterType="com.xxx.internet.demo.entity.UserInfo">        SELECT        *        FROM        `t_user_info`        <where>            <if test="phone != null">                `phone` = #{phone}            </if><!--            明文字段-->            <if test="secret != null">                AND `secret` = #{secret}            </if><!--            加密后字段-->            <if test="secretCiper != null">                AND `secret_ciper` = #{secretCiper}            </if>            <if test="name">                AND `name` = #{name}            </if>        </where>        ORDER BY `update_time` DESCv    </select></mapper>

做完下面的批改,咱们就能够编写加密插件了

@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }),        @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }) })public class ExecutorEncryptInterceptor implements Interceptor {    private static final ObjectFactory        DEFAULT_OBJECT_FACTORY         = new DefaultObjectFactory();     private static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();     private static final ReflectorFactory     REFLECTOR_FACTORY              = new DefaultReflectorFactory();     private static final List<String>         COLLECTION_NAME  = Arrays.asList("list");     private static final String               COUNT_SUFFIX                   = "_COUNT";     @Override    public Object intercept(Invocation invocation) throws Throwable {         // 获取拦截器拦挡的设置参数对象DefaultParameterHandler        final Object[] args = invocation.getArgs();        MappedStatement mappedStatement = (MappedStatement) args[0];        Object parameterObject = args[1];         // id字段对应执行的SQL的办法的全门路,蕴含类名和办法名        String id = mappedStatement.getId();        String className = id.substring(0, id.lastIndexOf("."));        String methodName = id.substring(id.lastIndexOf(".") + 1);         // 分页插件会生成一个count语句,这个语句的参数也要做解决        if (methodName.endsWith(COUNT_SUFFIX)) {            methodName = methodName.substring(0, methodName.lastIndexOf(COUNT_SUFFIX));        }         // 动静加载类并获取类中的办法        final Method[] methods = Class.forName(className).getMethods();         // 遍历类的所有办法并找到此次调用的办法        for (Method method : methods) {            if (method.getName().equalsIgnoreCase(methodName) && method.isAnnotationPresent(TEncrypt.class)) {                 // 获取办法上的注解以及注解对应的参数                TEncrypt paramAnnotation = method.getAnnotation(TEncrypt.class);                 // 反对加密的操作,这里只批改参数                if (parameterObject instanceof Map) {                    List<String> paramAnnotations = findParams(method);                    parameterMapHandler((Map) parameterObject, paramAnnotation, mappedStatement.getSqlCommandType(), paramAnnotations);                } else {                    encryptParam(parameterObject, paramAnnotation, mappedStatement.getSqlCommandType());                }            }        }         return invocation.proceed();    }}

加密的主体流程如下:

  1. 判断本次调用的办法上是否注解了@TEncrypt。
  2. 获取注解以及在注解上配置的参数。
  3. 遍历parameterObject,找到须要加密的字段。
  4. 调用加密办法,失去加密后的值。
  5. 将加密后的字段和值写入parameterObject。

难点次要在parameterObject的解析,到了Executor这一层,parameterObject曾经不再是简略的Object[],而是由MapperMethod.convertArgsToSqlCommandParam(Object[] args)办法创立的一个对象,既然要对这个对象做解决,咱们必定得先晓得它的创立过程。

参考上图parameterObject的创立过程,加密插件对parameterObject的解决实质上是一个逆向的过程。如果是list,咱们就遍历list里的每一个值,如果是map,咱们就遍历map里的每一个值。

失去须要解决的Object后,再遍历Object里的每个属性,判断是否在@TEncrypt注解的srcKeys参数中,如果是,则加密再设置到Object中。

解密插件的逻辑和加密插件基本一致,这里不再赘述。

五、问题挑战

5.1 分页插件主动生成count语句

业务代码里很多中央都用了 com.github.pagehelper 进行物理分页,参考上面的demo,在应用PageRowBounds时,pagehelper插件会帮咱们获取符合条件的数据总数并设置到rowBounds对象的total属性中。

PageRowBounds rowBounds = new PageRowBounds(0, 10);List<User> list = userMapper.selectIf(1, rowBounds);long total = rowBounds.getTotal();

那么问题来了,外表上看,咱们只执行了userMapper.selectIf(1, rowBounds)这一条语句,而pagehelper是通过改写SQL减少limit、offset实现的物理分页,在整个语句的执行过程中没有从数据库里把所有符合条件的数据读出来,那么pagehelper是怎么失去数据的总数的呢?

答案是pagehelper会再执行一条count语句。先不说额定一条执行count语句的原理,咱们先看看加了一条count语句会导致什么问题。

参考之前的selectUserList接口,假如咱们想抉择secret为某个值的数据,那么通过加密插件的解决后最终执行的大抵是这样一条语句 "select * from t\_user\_info where secret\_ciper = ? order by update\_time limit ?, ?"。

但因为pagehelper还会再执行一条语句,而因为该语句并没有 @TEncrypt 注解,所以是不会被加密插件拦挡的,最终执行的count语句是相似这样的: "select count(*) from t\_user\_info where secret = ? order by update_time"。

能够显著的看到第一条语句是应用secret_ciper作为查问条件,而count语句是应用secret作为查问条件,会导致最终失去的数据总量和理论的数据总量不统一。

因而咱们在加密插件的代码里对count语句做了非凡解决,因为pagehelper新增的count语句对应的mappedStatement的id固定以"\_COUNT"结尾,而这个id就是对应的mapper里的办法的全门路,举例来说原始语句的id是"com.xxx.internet.demo.entity.UserInfo.selectUserList",那么count语句的id就是"com.xxx.internet.demo.entity.UserInfo.selectUserList\_COUNT",去掉"_COUNT"后咱们再判断对应的办法上有没有注解就能够了。

六、总结

本文介绍了应用 MyBatis 插件实现数据库字段加解密的摸索过程,理论开发过程中须要留神的细节比拟多,整个流程下来我对 MyBatis 的了解也加深了。总的来说,这个计划比拟轻量,尽管对业务代码有侵入,但能把影响面管制到最小。