mybatis-plus 攔截器敏感字段加解密的實(shí)現(xiàn)
背景
數(shù)據(jù)庫(kù)在保存數(shù)據(jù)時(shí),對(duì)于某些敏感數(shù)據(jù)需要脫敏或者加密處理,如果一個(gè)一個(gè)的去加顯然工作量大而且容易出錯(cuò),這個(gè)時(shí)候可以考慮使用攔截器,本文針對(duì)的是mybatis-plus作為持久層框架,其他場(chǎng)景未測(cè)試。代碼如下:
一、查詢攔截器
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")注解的自定義類型 * 返回結(jié)果解密使用方式: ①在自定義的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 { /** * 查詢參數(shù)名稱,ParamMap的key值 */ private static final String DECRYPT = "decrypt"; @Autowired private CryptService cryptService; @Autowired private UpdateInterceptor updateInterceptor; @Override public Object intercept(Invocation invocation) throws Throwable { //獲取查詢參數(shù),查詢條件是否需要加密 Object[] args = invocation.getArgs(); Object parameter = args[1]; Object result = null; //設(shè)置執(zhí)行標(biāo)識(shí) 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)) { //執(zhí)行sql,還原加密后的報(bào)文 MappedStatement mappedStatement = (MappedStatement) args[0]; result = updateInterceptor.proceed(invocation, mappedStatement, queryParameter); flag = false; } } } //是否需要執(zhí)行 if (flag) { result = invocation.proceed(); } if (Objects.isNull(result)) { return null; } // 返回列表數(shù)據(jù),循環(huán)檢查 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); } //返回結(jié)果 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: 數(shù)據(jù)庫(kù)更新操作攔截器 * 一、支持的使用場(chǎng)景 * ①場(chǎng)景一:通過(guò)mybatis-plus BaseMapper自動(dòng)映射的方法 * ②場(chǎng)景一:通過(guò)mapper接口自定義的方法,更新對(duì)象為自定義DO * 二、使用方法 * ①在自定義的DO上加上注解 CryptAnnotation * ②在需要加解密的字段屬性上加上CryptAnnotation * ③自定義映射方法在需要加解密的自定義DO參數(shù)使用@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; /** * 更新參數(shù)名稱,ParamMap的key值 */ private static final String CRYPT = "et"; @Override public Object intercept(Invocation invocation) throws Throwable { //代理類方法參數(shù),該攔截器攔截的update方法有兩個(gè)參數(shù)args = {MappedStatement.class, Object.class} Object[] args = invocation.getArgs(); //獲取方法參數(shù) MappedStatement mappedStatement = (MappedStatement) args[0]; Object parameter = args[1]; if (Objects.isNull(parameter)) { //無(wú)參數(shù),直接放行 return invocation.proceed(); } // 如果是多個(gè)參數(shù)或使用Param注解(Param注解會(huì)將參數(shù)放置在ParamMap中) if (parameter instanceof MapperMethod.ParamMap) { Map paramMap = (Map) parameter; if (paramMap.containsKey(CRYPT)) { Object updateParameter = paramMap.get(CRYPT); if (needToCrypt(updateParameter)) { //執(zhí)行sql,還原加解密后的報(bào)文 return proceed(invocation, mappedStatement, updateParameter); } } } else if (parameter instanceof DefaultSqlSession.StrictMap) { //不知道是啥意思,直接過(guò) return invocation.proceed(); } else if (needToCrypt(parameter)) { //執(zhí)行sql,還原加解密后的報(bào)文 return proceed(invocation, mappedStatement, parameter); } //其他場(chǎng)景直接放行 return invocation.proceed(); } /** * 執(zhí)行sql,還原加解密后的報(bào)文 * * @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 { //先復(fù)制一個(gè)對(duì)象備份數(shù)據(jù) Object newInstance = newInstance(parameter); //調(diào)用加解密服務(wù) cryptService.encrypt(parameter); //執(zhí)行操作,得到返回結(jié)果 Object result = invocation.proceed(); //把加解密后的字段還原 reductionParameter(mappedStatement, newInstance, parameter); //返回結(jié)果 return result; } /** * 先復(fù)制一個(gè)對(duì)象備份數(shù)據(jù),便于加解密后還原原報(bào)文 * * @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; } /** * 把加解密后的字段還原,同時(shí)把mybatis返回的tableId返回給參數(shù)對(duì)象 * * @param mappedStatement * @param newInstance * @param parameter * @throws IllegalAccessException */ private void reductionParameter(MappedStatement mappedStatement, Object newInstance, Object parameter) throws IllegalAccessException { //獲取映射語(yǔ)句命令類型 SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType(); if (SqlCommandType.INSERT == sqlCommandType) { //從參數(shù)屬性中找到注解是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); //覆蓋參數(shù)加解密的值 BeanUtils.copyProperties(newInstance, parameter); field.set(parameter, id); } else { //覆蓋參數(shù)加解密的值 BeanUtils.copyProperties(newInstance, parameter); } } else { //覆蓋參數(shù)加解密的值 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) { //無(wú)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 為加密服務(wù),怎么實(shí)現(xiàn)自己可以根據(jù)實(shí)際情況來(lái)實(shí)現(xiàn)。
到此這篇關(guān)于mybatis-plus 攔截器敏感字段加解密的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)mybatis-plus 敏感字段加解密內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- MybatisPlus攔截器如何實(shí)現(xiàn)數(shù)據(jù)表分表
- mybatis-plus配置攔截器實(shí)現(xiàn)sql完整打印的代碼設(shè)計(jì)
- MyBatis-Plus攔截器實(shí)現(xiàn)數(shù)據(jù)權(quán)限控制的方法
- Mybatis-plus通過(guò)添加攔截器實(shí)現(xiàn)簡(jiǎn)單數(shù)據(jù)權(quán)限
- MybatisPlusInterceptor實(shí)現(xiàn)sql攔截器超詳細(xì)教程
- MyBatis-Plus攔截器實(shí)現(xiàn)數(shù)據(jù)權(quán)限控制的示例
- MyBatis-Plus攔截器對(duì)敏感數(shù)據(jù)實(shí)現(xiàn)加密
- mybatis-plus攔截器、字段填充器、類型處理器、表名替換、SqlInjector(聯(lián)合主鍵處理)
- mybatisplus 的SQL攔截器實(shí)現(xiàn)關(guān)聯(lián)查詢功能
- Mybatis Plus 3.4.0分頁(yè)攔截器的用法小結(jié)
相關(guān)文章
Java實(shí)現(xiàn)的Excel列號(hào)數(shù)字與字母互相轉(zhuǎn)換功能
這篇文章主要介紹了Java實(shí)現(xiàn)的Excel列號(hào)數(shù)字與字母互相轉(zhuǎn)換功能,涉及java針對(duì)Excel相關(guān)數(shù)值與字符串操作技巧,需要的朋友可以參考下2018-03-03SpringBoot實(shí)現(xiàn)自定義配置文件提示的方法
這篇文章主要介紹了SpringBoot實(shí)現(xiàn)自定義配置文件提示的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03SpringBoot整合canal實(shí)現(xiàn)數(shù)據(jù)同步的示例代碼
本文主要介紹了SpringBoot整合canal實(shí)現(xiàn)數(shù)據(jù)同步,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03zuul過(guò)濾器中轉(zhuǎn)發(fā)請(qǐng)求頭的解決方案
這篇文章主要介紹了zuul過(guò)濾器中轉(zhuǎn)發(fā)請(qǐng)求頭的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07使用Spring Boot快速構(gòu)建基于SQLite數(shù)據(jù)源的應(yīng)用
為了提供一個(gè)單包易部署的服務(wù)器應(yīng)用,考慮使用Spring Boot,因?yàn)槠浼闪薃pache Tomcat,易于運(yùn)行,免去絕大部分了服務(wù)器配置的步驟2017-08-08SpringBoot+MyBatis-Flex配置ProxySQL的實(shí)現(xiàn)步驟
本文主要介紹了SpringBoot+MyBatis-Flex配置ProxySQL的實(shí)現(xiàn)步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2025-02-02超詳細(xì)解析Spring Bean的創(chuàng)建過(guò)程
這篇文章主要揭秘了Spring Bean的創(chuàng)建過(guò)程,文中通過(guò)代碼示例和圖文結(jié)合的方式解析的超級(jí)詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-05-05Java使用EasyExcel進(jìn)行單元格合并的問(wèn)題詳解
項(xiàng)目中需要導(dǎo)出并合并指定的單元格,下面這篇文章主要給大家介紹了關(guān)于java評(píng)論、回復(fù)功能設(shè)計(jì)與實(shí)現(xiàn)的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-06-06