自定义注解+拦截器优雅的实现敏感数据的加解密!
一、什么是Mybatis Plugin
//语句执行拦截
Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
// 参数获取、设置时进行拦截
ParameterHandler (getParameterObject, setParameters)
// 对返回结果进行拦截
ResultSetHandler (handleResultSets, handleOutputParameters)
//sql语句拦截
StatementHandler (prepare, parameterize, batch, update, query)
二、实现基于注解的敏感信息加解密拦截器
2.1 实现思路
public interface Interceptor {
//主要参数拦截方法
Object intercept(Invocation invocation) throws Throwable;
//mybatis插件链
default Object plugin(Object target) {return Plugin.wrap(target, this);}
//自定义插件配置文件方法
default void setProperties(Properties properties) {}
}
2.2 定义需要加密解密的敏感信息注解
/**
* 注解敏感信息类的注解
*/
@Inherited
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface SensitiveData {
}
/**
* 注解敏感信息类中敏感字段的注解
*/
@Inherited
@Target({ ElementType.Field })
@Retention(RetentionPolicy.RUNTIME)
public @interface SensitiveField {
}
2.3 定义加密接口及其实现类
public interface EncryptUtil {
/**
* 加密
*
* @param declaredFields paramsObject所声明的字段
* @param paramsObject mapper中paramsType的实例
* @return T
* @throws IllegalAccessException 字段不可访问异常
*/
T encrypt(Field[] declaredFields, T paramsObject) throws IllegalAccessException;
}
@Component
public class AESEncrypt implements EncryptUtil {
@Autowired
AESUtil aesUtil;
/**
* 加密
*
* @param declaredFields paramsObject所声明的字段
* @param paramsObject mapper中paramsType的实例
* @return T
* @throws IllegalAccessException 字段不可访问异常
*/
@Override
publicT encrypt(Field[] declaredFields, T paramsObject) throws IllegalAccessException {
for (Field field : declaredFields) {
//取出所有被EncryptDecryptField注解的字段
SensitiveField sensitiveField = field.getAnnotation(SensitiveField.class);
if (!Objects.isNull(sensitiveField)) {
field.setAccessible(true);
Object object = field.get(paramsObject);
//暂时只实现String类型的加密
if (object instanceof String) {
String value = (String) object;
//加密 这里我使用自定义的AES加密工具
field.set(paramsObject, aesUtil.encrypt(value));
}
}
}
return paramsObject;
}
}
2.4 实现入参加密拦截器
org.apache.ibatis.plugin.Interceptor
拦截器接口要求我们实现以下三个方法public interface Interceptor {
//核心拦截逻辑
Object intercept(Invocation invocation) throws Throwable;
//拦截器链
default Object plugin(Object target) {return Plugin.wrap(target, this);}
//自定义配置文件操作
default void setProperties(Properties properties) { }
}
@Intercepts
注解开启拦截器,@Signature
注解定义拦截器的实际类型。type 属性指定当前拦截器使用StatementHandler 、ResultSetHandler、ParameterHandler,Executor的一种
method 属性指定使用以上四种类型的具体方法(可进入class内部查看其方法)。
args 属性指定预编译语句
/**
* 加密拦截器
* 注意@Component注解一定要加上
*
* @author : tanzj
* @date : 2020/1/19.
*/
@Slf4j
@Component
@Intercepts({
@Signature(type = ParameterHandler.class, method = "setParameters", args = PreparedStatement.class),
})
public class EncryptInterceptor implements Interceptor {
private final EncryptDecryptUtil encryptUtil;
@Autowired
public EncryptInterceptor(EncryptDecryptUtil encryptUtil) {
this.encryptUtil = encryptUtil;
}
@Override
@Override
public Object intercept(Invocation invocation) throws Throwable {
//@Signature 指定了 type= parameterHandler 后,这里的 invocation.getTarget() 便是parameterHandler
//若指定ResultSetHandler ,这里则能强转为ResultSetHandler
ParameterHandler parameterHandler = (ParameterHandler) invocation.getTarget();
// 获取参数对像,即 mapper 中 paramsType 的实例
Field parameterField = parameterHandler.getClass().getDeclaredField("parameterObject");
parameterField.setAccessible(true);
//取出实例
Object parameterObject = parameterField.get(parameterHandler);
if (parameterObject != null) {
Class> parameterObjectClass = parameterObject.getClass();
//校验该实例的类是否被@SensitiveData所注解
SensitiveData sensitiveData = AnnotationUtils.findAnnotation(parameterObjectClass, SensitiveData.class);
if (Objects.nonNull(sensitiveData)) {
//取出当前当前类所有字段,传入加密方法
Field[] declaredFields = parameterObjectClass.getDeclaredFields();
encryptUtil.encrypt(declaredFields, parameterObject);
}
}
return invocation.proceed();
}
/**
* 切记配置,否则当前拦截器不会加入拦截器链
*/
@Override
public Object plugin(Object o) {
return Plugin.wrap(o, this);
}
//自定义配置写入,没有自定义配置的可以直接置空此方法
@Override
public void setProperties(Properties properties) {
}
}
2.5 定义解密接口及其实现类
public interface DecryptUtil {
/**
* 解密
*
* @param result resultType的实例
* @return T
* @throws IllegalAccessException 字段不可访问异常
*/
T decrypt(T result) throws IllegalAccessException;
}
public class AESDecrypt implements DecryptUtil {
@Autowired
AESUtil aesUtil;
/**
* 解密
*
* @param result resultType的实例
* @return T
* @throws IllegalAccessException 字段不可访问异常
*/
@Override
publicT decrypt(T result) throws IllegalAccessException {
//取出resultType的类
Class> resultClass = result.getClass();
Field[] declaredFields = resultClass.getDeclaredFields();
for (Field field : declaredFields) {
//取出所有被EncryptDecryptField注解的字段
SensitiveField sensitiveField = field.getAnnotation(SensitiveField.class);
if (!Objects.isNull(sensitiveField)) {
field.setAccessible(true);
Object object = field.get(result);
//只支持String的解密
if (object instanceof String) {
String value = (String) object;
//对注解的字段进行逐一解密
field.set(result, aesUtil.decrypt(value));
}
}
}
return result;
}
}
2.6 定义出参解密拦截器
@Slf4j
@Component
@Intercepts({
@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})
})
public class DecryptInterceptor implements Interceptor {
@Autowired
DecryptUtil aesDecrypt;
@Override
public Object intercept(Invocation invocation) throws Throwable {
//取出查询的结果
Object resultObject = invocation.proceed();
if (Objects.isNull(resultObject)) {
return null;
}
//基于selectList
if (resultObject instanceof ArrayList) {
ArrayList resultList = (ArrayList) resultObject;
if (!CollectionUtils.isEmpty(resultList) && needToDecrypt(resultList.get(0))) {
for (Object result : resultList) {
//逐一解密
aesDecrypt.decrypt(result);
}
}
//基于selectOne
} else {
if (needToDecrypt(resultObject)) {
aesDecrypt.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) {
}
}
3、注解实体类中需要加解密的字段
paramType=User
resultType=User
便可实现脱离业务层,基于mybatis拦截器的加解密操作。推荐阅读:
内容包含Java基础、JavaWeb、MySQL性能优化、JVM、锁、百万并发、消息队列、高性能缓存、反射、Spring全家桶原理、微服务、Zookeeper、数据结构、限流熔断降级......等技术栈!
⬇戳阅读原文领取! 朕已阅
评论