可以从图中看出Mybatis可以被拦截的类型按先后顺序有以下四种:
1.Executor:拦截执行器的方法。
2.StatementHandler:拦截Sql语法构建的处理。
3.ParameterHandler:拦截参数的处理。
4.ResultHandler:拦截结果集的处理。
Intercepts注解需要一个Signature(拦截点)参数数组。通过Signature来指定拦截哪个对象里面的哪个方法。@Intercepts注解定义如下:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Intercepts {
/**
* 定义拦截点
* 只有符合拦截点的条件才会进入到拦截器
*/
Signature[] value();
}
Signature来指定咱们需要拦截那个类对象的哪个方法。定义如下:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface Signature {
/**
* 定义拦截的类 Executor、ParameterHandler、StatementHandler、ResultSetHandler当中的一个
*/
Class<?> type();
/**
* 在定义拦截类的基础之上,在定义拦截的方法
*/
String method();
/**
* 在定义拦截方法的基础之上在定义拦截的方法对应的参数,
* JAVA里面方法可能重载,故注意参数的类型和顺序
*/
Class<?>[] args();
}
标识拦截注解@Intercepts规则使用,简单实例如下:
@Intercepts({//注意看这个大花括号,也就这说这里可以定义多个@Signature对多个地方拦截,都用这个拦截器
@Signature(
type = ResultSetHandler.class,
method = "handleResultSets",
args = {Statement.class}),
@Signature(type = Executor.class,
method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
说明: @Intercepts:标识该类是一个拦截器; @Signature:指明自定义拦截器需要拦截哪一个类型,哪一个方法;
- type:上述四种类型中的一种;
- method:对应接口中的哪类方法(因为可能存在重载方法);
- args:对应哪一个方法的入参;
谈到自定义拦截器实践部分,主要按照以下三步:
1.实现org.apache.ibatis.plugin.Interceptor接口,重写以下方法:
public interface Interceptor {
Object intercept(Invocation var1) throws Throwable;
Object plugin(Object var1);
void setProperties(Properties var1);
}
plugin(Object target)
这个方法的作用是就是让mybatis判断,是否要进行拦截,然后做出决定是否生成一个代理。
@Override
public Object plugin(Object target) {
// 只对要拦截制定类型的对象生成代理
if(target instanceof Executor){
// 调用插件
return Plugin.wrap(target, this);
}
return target;
}
setProperties(Properties properties)
拦截器需要一些变量对象,而且这个对象是支持可配置的。
在项目中需要对用户敏感数据进行脱敏处理,例如身份号、手机号等信息进行加密再入库。
设置对参数中带有敏感参数字段的数据时进行加密
对返回的结果进行解密处理
根据不同的要求,我们只需要对 ParameterHandler 和 ResultSetHandler 进行切入。定义特定注解,在切入时需要检查字段中是否包含注解来是否加解密。
加注解
定义 SensitiveData 注解
import java.lang.annotation.*;
/**
* 该注解定义在类上
* 插件通过扫描类对象是否包含这个注解来决定是否继续扫描其中的字段注解
* 这个注解要配合EncryptTransaction注解
**/
@Inherited
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface SensitiveData {
}
定义 EncryptTransaction 注解
import java.lang.annotation.*;
/**
* 该注解有两种使用方式
* ①:配合@SensitiveData加在类中的字段上
* ②:直接在Mapper中的方法参数上使用
**/
@Documented
@Inherited
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface EncryptTransaction {
}
加解密工具类
解密
package sicnu.cs.ich.common.interceptor.transaction.service;
public interface IDecryptUtil {
/**
* 解密
*
* @param result resultType的实例
* @return T
* @throws IllegalAccessException 字段不可访问异常
*/
<T> T decrypt(T result) throws IllegalAccessException;
}
加密
加密接口
package sicnu.cs.ich.common.interceptor.transaction.service;
import java.lang.reflect.Field;
public interface IEncryptUtil {
/**
* 加密
*
* @param declaredFields 加密字段
* @param paramsObject 对象
* @param 入参类型
* @return 返回加密
* @throws IllegalAccessException 不可访问
*/
<T> T encrypt(Field[] declaredFields, T paramsObject) throws IllegalAccessException;
}
加密实现类
package sicnu.cs.ich.common.interceptor.transaction.service.impl;
import com.fasterxml.jackson.databind.ObjectReader;
import org.springframework.stereotype.Component;
import sicnu.cs.ich.api.common.annotations.transaction.EncryptTransaction;
import sicnu.cs.ich.common.interceptor.transaction.service.IEncryptUtil;
import sicnu.cs.ich.common.util.keyCryptor.DBAESUtil;
import java.io.ObjectInputStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Objects;
import java.util.Random;
@Component
public class EncryptUtilImpl implements IEncryptUtil {
@Override
public <T> T encrypt(Field[] declaredFields, T paramsObject) throws IllegalAccessException {
//取出所有被EncryptTransaction注解的字段
for (Field field : declaredFields) {
EncryptTransaction encryptTransaction = field.getAnnotation(EncryptTransaction.class);
if (!Objects.isNull(encryptTransaction)) {
field.setAccessible(true);
Object object = field.get(paramsObject);
//暂时只实现String类型的加密
if (object instanceof String) {
String value = (String) object;
//加密
try {
field.set(paramsObject, DBAESUtil.encrypt(value));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return paramsObject;
}
}
解密实现类
package sicnu.cs.ich.common.interceptor.transaction.service.impl;
import org.springframework.stereotype.Component;
import sicnu.cs.ich.api.common.annotations.transaction.EncryptTransaction;
import sicnu.cs.ich.common.interceptor.transaction.service.IDecryptUtil;
import sicnu.cs.ich.common.util.keyCryptor.DBAESUtil;
import java.lang.reflect.Field;
import java.util.Objects;
@Component
public class DecryptImpl implements IDecryptUtil {
/**
* 解密
*
* @param result resultType的实例
*/
@Override
public <T> T decrypt(T result) throws IllegalAccessException {
//取出resultType的类
Class<?> resultClass = result.getClass();
Field[] declaredFields = resultClass.getDeclaredFields();
for (Field field : declaredFields) {
//取出所有被DecryptTransaction注解的字段
EncryptTransaction encryptTransaction = field.getAnnotation(EncryptTransaction.class);
if (!Objects.isNull(encryptTransaction)) {
field.setAccessible(true);
Object object = field.get(result);
//String的解密
if (object instanceof String) {
String value = (String) object;
//对注解的字段进行逐一解密
try {
field.set(result, DBAESUtil.decrypt(value));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return result;
}
}
加解密工具类
package sicnu.cs.ich.common.util.keyCryptor;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class DBAESUtil {
private static final String DEFAULT_V = "6859505890402435";
// 自己填写
private static final String KEY = "***";
private static final String ALGORITHM = "AES";
private static SecretKeySpec getKey() {
byte[] arrBTmp = DBAESUtil.KEY.getBytes();
// 创建一个空的16位字节数组(默认值为0)
byte[] arrB = new byte[16];
for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
arrB[i] = arrBTmp[i];
}
return new SecretKeySpec(arrB, ALGORITHM);
}
/**
* 加密
*/
public static String encrypt(String content) throws Exception {
final Base64.Encoder encoder = Base64.getEncoder();
SecretKeySpec keySpec = getKey();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(DEFAULT_V.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
byte[] encrypted = cipher.doFinal(content.getBytes());
return encoder.encodeToString(encrypted);
}
/**
* 解密
*/
public static String decrypt(String content) throws Exception {
final Base64.Decoder decoder = Base64.getDecoder();
SecretKeySpec keySpec = getKey();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(DEFAULT_V.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
byte[] base64 = decoder.decode(content);
byte[] original = cipher.doFinal(base64);
return new String(original);
}
}
插件实现
参数插件 ParameterInterceptor
切入 Mybatis 设置参数时对敏感数据进行加密
Mybatis 插件的使用就是通过实现 Mybatis 中的 Interceptor 接口
再 @Intercepts 注解
// 使用mybatis插件时需要定义签名
// type标识需要切入的Handler
// method表示要要切入的方法
@Intercepts({
@Signature(type = ParameterHandler.class, method = “setParameters”, args = PreparedStatement.class),
})
package sicnu.cs.ich.common.interceptor.transaction;
import com.baomidou.mybatisplus.core.MybatisParameterHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import sicnu.cs.ich.api.common.annotations.transaction.EncryptTransaction;
import sicnu.cs.ich.api.common.annotations.transaction.SensitiveData;
import sicnu.cs.ich.common.interceptor.transaction.service.IEncryptUtil;
import sicnu.cs.ich.common.util.keyCryptor.DBAESUtil;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.sql.PreparedStatement;
import java.util.*;
@Slf4j
// 注入Spring
@Component
@Intercepts({
@Signature(type = ParameterHandler.class, method = "setParameters", args = PreparedStatement.class),
})
public class ParameterInterceptor implements Interceptor {
@Autowired
private IEncryptUtil IEncryptUtil;
@Override
public Object intercept(Invocation invocation) throws Throwable {
//@Signature 指定了 type= parameterHandler 后,这里的 invocation.getTarget() 便是parameterHandler
//若指定ResultSetHandler ,这里则能强转为ResultSetHandler
MybatisParameterHandler parameterHandler = (MybatisParameterHandler) invocation.getTarget();
// 获取参数对像,即 mapper 中 paramsType 的实例
Field parameterField = parameterHandler.getClass().getDeclaredField("parameterObject");
parameterField.setAccessible(true);
//取出实例
Object parameterObject = parameterField.get(parameterHandler);
// 搜索该方法中是否有需要加密的普通字段
List<String> paramNames = searchParamAnnotation(parameterHandler);
if (parameterObject != null) {
Class<?> parameterObjectClass = parameterObject.getClass();
//对类字段进行加密
//校验该实例的类是否被@SensitiveData所注解
SensitiveData sensitiveData = AnnotationUtils.findAnnotation(parameterObjectClass, SensitiveData.class);
if (Objects.nonNull(sensitiveData)) {
//取出当前当前类所有字段,传入加密方法
Field[] declaredFields = parameterObjectClass.getDeclaredFields();
IEncryptUtil.encrypt(declaredFields, parameterObject);
}
// 对普通字段进行加密
if (!CollectionUtils.isEmpty(paramNames)) {
// 反射获取 BoundSql 对象,此对象包含生成的sql和sql的参数map映射
Field boundSqlField = parameterHandler.getClass().getDeclaredField("boundSql");
boundSqlField.setAccessible(true);
BoundSql boundSql = (BoundSql) boundSqlField.get(parameterHandler);
PreparedStatement ps = (PreparedStatement) invocation.getArgs()[0];
// 改写参数
processParam(parameterObject, paramNames);
// 改写的参数设置到原parameterHandler对象
parameterField.set(parameterHandler, parameterObject);
parameterHandler.setParameters(ps);
}
}
return invocation.proceed();
}
private void processParam(Object parameterObject, List<String> params) throws Exception {
// 处理参数对象 如果是 map 且map的key 中没有 tenantId,添加到参数map中
// 如果参数是bean,反射设置值
if (parameterObject instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, String> map = ((Map<String, String>) parameterObject);
for (String param : params) {
String value = map.get(param);
map.put(param, value==null?null:DBAESUtil.encrypt(value));
}
// parameterObject = map;
}
}
private List<String> searchParamAnnotation(ParameterHandler parameterHandler) throws NoSuchFieldException, ClassNotFoundException, IllegalAccessException {
Class<MybatisParameterHandler> handlerClass = MybatisParameterHandler.class;
Field mappedStatementFiled = handlerClass.getDeclaredField("mappedStatement");
mappedStatementFiled.setAccessible(true);
MappedStatement mappedStatement = (MappedStatement) mappedStatementFiled.get(parameterHandler);
String methodName = mappedStatement.getId();
Class<?> mapperClass = Class.forName(methodName.substring(0, methodName.lastIndexOf('.')));
methodName = methodName.substring(methodName.lastIndexOf('.') + 1);
Method[] methods = mapperClass.getDeclaredMethods();
Method method = null;
for (Method m : methods) {
if (m.getName().equals(methodName)) {
method = m;
break;
}
}
List<String> paramNames = null;
if (method != null) {
Annotation[][] pa = method.getParameterAnnotations();
Parameter[] parameters = method.getParameters();
for (int i = 0; i < pa.length; i++) {
for (Annotation annotation : pa[i]) {
if (annotation instanceof EncryptTransaction) {
if (paramNames == null) {
paramNames = new ArrayList<>();
}
paramNames.add(parameters[i].getName());
}
}
}
}
return paramNames;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
返回值插件 ResultSetIntercepto
package sicnu.cs.ich.common.interceptor.transaction;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import sicnu.cs.ich.api.common.annotations.transaction.SensitiveData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Properties;
@Slf4j
@Component
@Intercepts({
@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})
})
public class ResultSetInterceptor implements Interceptor {
@Autowired
private sicnu.cs.ich.common.interceptor.transaction.service.IDecryptUtil IDecryptUtil;
@Override
public Object intercept(Invocation invocation) throws Throwable {
//取出查询的结果
Object resultObject = invocation.proceed();
if (Objects.isNull(resultObject)) {
return null;
}
//基于selectList
if (resultObject instanceof ArrayList) {
@SuppressWarnings("unchecked")
ArrayList<Objects> resultList = (ArrayList<Objects>) resultObject;
if (!CollectionUtils.isEmpty(resultList) && needToDecrypt(resultList.get(0))) {
for (Object result : resultList) {
//逐一解密
IDecryptUtil.decrypt(result);
}
}
//基于selectOne
} else {
if (needToDecrypt(resultObject)) {
IDecryptUtil.decrypt(resultObject);
}
}
return resultObject;
}
private boolean needToDecrypt(Object object) {
Class<?> objectClass = object.getClass();
SensitiveData sensitiveData = AnnotationUtils.findAnnotation(objectClass, SensitiveData.class);
return Objects.nonNull(sensitiveData);
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
使用
注意解在实体类上
import lombok.*;
import org.springframework.security.core.userdetails.UserDetails;
import sicnu.cs.ich.api.common.annotations.transaction.EncryptTransaction;
import sicnu.cs.ich.api.common.annotations.transaction.SensitiveData;
@With
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
@SensitiveData // 插件只对加了该注解的类进行扫描,只有加了这个注解的类才会生效
public class User implements Serializable {
private Integer id;
private String username;
private String openId;
private String password;
// 表明对该字段进行加密
@EncryptTransaction
private String email;
// 表明对该字段进行加密
@EncryptTransaction
private String mobile;
private Date createTime;
private Date expireTime;
private Boolean status = true;
}
注解在参数上
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import sicnu.cs.ich.api.common.annotations.transaction.EncryptTransaction;
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 只需要在参数前加上@EncryptTransaction 即可
long countByEmail(@EncryptTransaction @Param("email") String email);
long countByMobile(@EncryptTransaction @Param("mobile") String mobile);
}
参考:https://zhuanlan.zhihu.com/p/286476884
https://mp.weixin.qq.com/s/QMiN_uRDSec2fzjnZcPrNA