欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

mybatis-plus 攔截器敏感字段加解密的實(shí)現(xiàn)

 更新時(shí)間:2021年11月09日 09:17:47   作者:溫暖的伯  
數(shù)據(jù)庫(kù)在保存數(shù)據(jù)時(shí),對(duì)于某些敏感數(shù)據(jù)需要脫敏或者加密處理,本文主要介紹了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)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論