欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mybatis-plus 拦截器敏感字段加解密的实现

程序员文章站 2022-03-21 16:28:49
目录背景一、查询拦截器二、插入和更新拦截器三、注解背景数据库在保存数据时,对于某些敏感数据需要脱敏或者加密处理,如果一个一个的去加显然工作量大而且容易出错,这个时候可以考虑使用拦截器,本文针对的是my...

背景

数据库在保存数据时,对于某些敏感数据需要脱敏或者加密处理,如果一个一个的去加显然工作量大而且容易出错,这个时候可以考虑使用拦截器,本文针对的是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 为加密服务,怎么实现自己可以根据实际情况来实现。

到此这篇关于mybatis-plus 拦截器敏感字段加解密的实现的文章就介绍到这了,更多相关mybatis-plus 敏感字段加解密内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!