mybatis-plus * 敏感字段加解密的实现
作者:温暖的伯 发布时间:2023-12-20 05:58:17
标签:mybatis-plus,敏感字段,加解密
背景
数据库在保存数据时,对于某些敏感数据需要脱敏或者加密处理,如果一个一个的去加显然工作量大而且容易出错,这个时候可以考虑使用 * ,本文针对的是mybatis-plus作为持久层框架,其他场景未测试。代码如下:
一、查询 *
package com.sfpay.merchant.service.interceptor;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.sfpay.merchant.service.service.CryptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.Map;
import java.util.Objects;
/**
* @describe: 查询 *
* 查询条件加密使用方式:使用 @Param("decrypt")注解的自定义类型
* 返回结果解密使用方式: ①在自定义的DO上加上注解 CryptAnnotation ②在需要加解密的字段属性上加上CryptAnnotation
* @author: ***
* @date: 2021/3/30 17:51
*/
@Slf4j
@Intercepts({
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
RowBounds.class, ResultHandler.class})
})
public class QueryInterceptor implements Interceptor {
/**
* 查询参数名称,ParamMap的key值
*/
private static final String DECRYPT = "decrypt";
@Autowired
private CryptService cryptService;
@Autowired
private UpdateInterceptor updateInterceptor;
@Override
public Object intercept(Invocation invocation) throws Throwable {
//获取查询参数,查询条件是否需要加密
Object[] args = invocation.getArgs();
Object parameter = args[1];
Object result = null;
//设置执行标识
boolean flag = true;
if (parameter instanceof MapperMethod.ParamMap) {
Map paramMap = (Map) parameter;
if (paramMap.containsKey(DECRYPT)) {
Object queryParameter = paramMap.get(DECRYPT);
if (updateInterceptor.needToCrypt(queryParameter)) {
//执行sql,还原加密后的报文
MappedStatement mappedStatement = (MappedStatement) args[0];
result = updateInterceptor.proceed(invocation, mappedStatement, queryParameter);
flag = false;
}
}
}
//是否需要执行
if (flag) {
result = invocation.proceed();
}
if (Objects.isNull(result)) {
return null;
}
// 返回列表数据,循环检查
if (result instanceof ArrayList) {
ArrayList resultList = (ArrayList) result;
if (CollectionUtils.isNotEmpty(resultList) && updateInterceptor.needToCrypt(resultList.get(0))) {
for (Object o : resultList) {
cryptService.decrypt(o);
}
}
} else if (updateInterceptor.needToCrypt(result)) {
cryptService.decrypt(result);
}
//返回结果
return result;
}
}
二、插入和更新 *
package com.sfpay.merchant.service.interceptor;
import com.baomidou.mybatisplus.annotation.TableId;
import com.sfpay.merchant.common.util.annotation.CryptAnnotation;
import com.sfpay.merchant.service.service.CryptService;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.defaults.DefaultSqlSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
/**
* @describe: 数据库更新操作 *
* 一、支持的使用场景
* ①场景一:通过mybatis-plus BaseMapper自动映射的方法
* ②场景一:通过mapper接口自定义的方法,更新对象为自定义DO
* 二、使用方法
* ①在自定义的DO上加上注解 CryptAnnotation
* ②在需要加解密的字段属性上加上CryptAnnotation
* ③自定义映射方法在需要加解密的自定义DO参数使用@Param("et")
* @author: ***
* @date: 2021/3/31 17:51
*/
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class UpdateInterceptor implements Interceptor {
@Autowired
private CryptService cryptService;
/**
* 更新参数名称,ParamMap的key值
*/
private static final String CRYPT = "et";
@Override
public Object intercept(Invocation invocation) throws Throwable {
//代理类方法参数,该 * 拦截的update方法有两个参数args = {MappedStatement.class, Object.class}
Object[] args = invocation.getArgs();
//获取方法参数
MappedStatement mappedStatement = (MappedStatement) args[0];
Object parameter = args[1];
if (Objects.isNull(parameter)) {
//无参数,直接放行
return invocation.proceed();
}
// 如果是多个参数或使用Param注解(Param注解会将参数放置在ParamMap中)
if (parameter instanceof MapperMethod.ParamMap) {
Map paramMap = (Map) parameter;
if (paramMap.containsKey(CRYPT)) {
Object updateParameter = paramMap.get(CRYPT);
if (needToCrypt(updateParameter)) {
//执行sql,还原加解密后的报文
return proceed(invocation, mappedStatement, updateParameter);
}
}
} else if (parameter instanceof DefaultSqlSession.StrictMap) {
//不知道是啥意思,直接过
return invocation.proceed();
} else if (needToCrypt(parameter)) {
//执行sql,还原加解密后的报文
return proceed(invocation, mappedStatement, parameter);
}
//其他场景直接放行
return invocation.proceed();
}
/**
* 执行sql,还原加解密后的报文
*
* @param invocation
* @param mappedStatement
* @param parameter
* @return
* @throws IllegalAccessException
* @throws InstantiationException
* @throws InvocationTargetException
*/
Object proceed(Invocation invocation, MappedStatement mappedStatement, Object parameter) throws IllegalAccessException, InstantiationException, InvocationTargetException {
//先复制一个对象备份数据
Object newInstance = newInstance(parameter);
//调用加解密服务
cryptService.encrypt(parameter);
//执行操作,得到返回结果
Object result = invocation.proceed();
//把加解密后的字段还原
reductionParameter(mappedStatement, newInstance, parameter);
//返回结果
return result;
}
/**
* 先复制一个对象备份数据,便于加解密后还原原报文
*
* @param parameter
* @return
* @throws IllegalAccessException
* @throws InstantiationException
*/
private Object newInstance(Object parameter) throws IllegalAccessException, InstantiationException {
Object newInstance = parameter.getClass().newInstance();
BeanUtils.copyProperties(parameter, newInstance);
return newInstance;
}
/**
* 把加解密后的字段还原,同时把mybatis返回的tableId返回给参数对象
*
* @param mappedStatement
* @param newInstance
* @param parameter
* @throws IllegalAccessException
*/
private void reductionParameter(MappedStatement mappedStatement, Object newInstance, Object parameter) throws IllegalAccessException {
//获取映射语句命令类型
SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
if (SqlCommandType.INSERT == sqlCommandType) {
//从参数属性中找到注解是TableId的字段
Field[] parameterFields = parameter.getClass().getDeclaredFields();
Optional<Field> optional = Arrays.stream(parameterFields).filter(field -> field.isAnnotationPresent(TableId.class)).findAny();
if (optional.isPresent()) {
Field field = optional.get();
field.setAccessible(true);
Object id = field.get(parameter);
//覆盖参数加解密的值
BeanUtils.copyProperties(newInstance, parameter);
field.set(parameter, id);
} else {
//覆盖参数加解密的值
BeanUtils.copyProperties(newInstance, parameter);
}
} else {
//覆盖参数加解密的值
BeanUtils.copyProperties(newInstance, parameter);
}
}
/**
* 是否需要加解密:
* ①是否属于基本类型,void类型和String类型,如果是,不加解密
* ②DO上是否有注解 ③ 属性是否有注解
*
* @param object
* @return
*/
public boolean needToCrypt(Object object) {
if (object == null) {
return false;
}
Class<?> clazz = object.getClass();
if (clazz.isPrimitive() || object instanceof String) {
//基本类型和字符串不加解密
return false;
}
//获取DO注解
boolean annotationPresent = clazz.isAnnotationPresent(CryptAnnotation.class);
if (!annotationPresent) {
//无DO注解不加解密
return false;
}
//获取属性注解
Field[] fields = clazz.getDeclaredFields();
return Arrays.stream(fields).anyMatch(field -> field.isAnnotationPresent(CryptAnnotation.class));
}
}
三、注解
import com.sfpay.merchant.common.constant.EncryptDataTypeEnum;
import java.lang.annotation.*;
/**
* @author ***
* @Date 2020/12/30 20:13
* @description 加密注解类
* @Param
* @return
**/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
@Documented
@Inherited
public @interface CryptAnnotation {
EncryptDataTypeEnum type() default EncryptDataTypeEnum.OTHER;
}
cryptService 为加密服务,怎么实现自己可以根据实际情况来实现。
来源:https://blog.csdn.net/u010038477/article/details/115480655


猜你喜欢
- 对一个对象进行属性分析,并得到相应的属性值,并判断属性的默认值以及空值 public class People
- 昨天直接在机器上配置了Maven环境,今天顺便把Eclipse等IDE环境配置好。安装IDE Plugins的方法有很多。其一:在线安装,通
- 1 前言在项目开发中,异步化处理是非常常见的解决问题的手段,异步化处理除了使用线程池之外,还可以使用 CompletableFut
- 在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现。文件上传概述1、文件上传
- 在程序中对文件进行压缩解压缩是很重要的功能,不仅能减小文件的体积,还能对文件起到保护作用。如果是生成用户可以下载的文件,还可以极大的减少网络
- @ApiModel使用场景在实体类上边使用,标记类时swagger的解析类概述提供有关swagger模型的其它信息,类将在操作中用作类型时自
- 本文实例为大家分享了Android封装MVP实现登录注册功能,供大家参考,具体内容如下model包:import com.bwei.mvps
- java 出现Zipexception 异常的解决办法1 异常描述在从 SVN 检出项目并配置完成后,启动 Tomcat 服务器,报出如下错
- 本文实例讲解了iOS从背景图中取色的代码,分享给大家供大家参考,具体内容如下实现代码:void *bitmapData; //内存空间的指针
- 本文实例讲述了C#分布式事务的超时处理的方法。分享给大家供大家参考。具体分析如下:事务是个很精妙的存在,我们在数据层、服务层、业务逻辑层等多
- 博主最近在做一个内网项目,内部可以访问外部数据,但是外部访问不了内部数据,这也就造成了可能文件无法上传,所以博主另辟蹊径,在本地服务器上建立
- 本文实例为大家分享了C#实现简单的计算器功能的具体代码,供大家参考,具体内容如下环境:VS2010及以上版本1、建立个Window窗体应用2
- 自定义注解+springAop参数非空校验自定义注解,来对对应的方法进行入参校验,为空返回参数错误新建注解类@interface Param
- 短信是手机常见的功能,本文就以实例形式讲述了Android实现将已发送的短信写入短信数据库的方法。分享给大家供大家参考之用。具体如下:一般来
- 基本的 Java 类型(boolean、byte、char、short、int、long、float 和 double)和关键字 void通
- 目录文件下载文件上传 * * 的配置多个 * 的执行顺序异常处理器基于配置的异常处理基于注解的异常处理总结文件下载使用ResponseEn
- 前言Condition是在Spring4.0增加的条件判断功能,通过这个功能可以实现选择性的创建Bean对象。引入一个例子SpringBoo
- 目录1、如果一个方法或变量是"private"访问级别,那么它的访问范围是:2、代码将打印?3、下面关于hibernat
- 1、通过查找API文档:2、Map.Entry是一个接口,所以不能直接实例化。3、Map.entrySet( )返回的是一个collecti
- 前言博主上个礼拜,已经实现了quarkus的native image应用的上线,经过两天的监控下来,一切运行指标良好,就是内存升到了100M