• mybatis用拦截器实现字段加解密


    前言

    根据公司业务需要,灵活对客户敏感信息进行加解密,这里采用mybatis拦截器进行简单实现个demo。

    拦截器的使用

    // 执行
    Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
    // 请求参数处理
    ParameterHandler (getParameterObject, setParameters)
    // 返回结果集处理
    ResultSetHandler (handleResultSets, handleOutputParameters)
    // SQL语句构建
    StatementHandler (prepare, parameterize, batch, update, query)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    我们要实现数据加密,进入数据库的字段不能是真实的数据,但是返回来的数据要真实可用,所以我们需要针对 Parameter 和 ResultSet 两种类型处理,同时为了更灵活的使用,我们需要自定义注解。

    /**
     *需要加解密的字段注解
    **/
    @Target({ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Encryption {
        String encryptionType() default "";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    编写一下加解密算法(随便找的)

    **
     * @desc: AES对称加密,对明文进行加密、解密处理
     * @author:
     * @createTime: 20231014 上午9:54:52
     * @version: v0.0.1
     */
    public class AESUtil {
        private static final String KEY_ALGORITHM = "AES";
        private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    
    
        /**
         * @desc: AES对称-加密操作
         * @version: v0.0.1
         * @param keyStr 进行了Base64编码的秘钥
         * @param data 需要进行加密的原文
         * @return String 数据密文,加密后的数据,进行了Base64的编码
         */
        public static String encrypt(String keyStr, String data) throws Exception {
            // 转换密钥
            Key key = new SecretKeySpec(Base64.getDecoder().decode(keyStr), KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            // 加密
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = cipher.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(result);
        }
        /**
         * @desc: AES对称-解密操作
         * @version: v0.0.1
         * @param keyStr 进行了Base64编码的秘钥
         * @param data 需要解密的数据(数据必须是通过AES进行加密后,对加密数据Base64编码的数据)
         * @return String 返回解密后的原文
         */
        public static String decrypt(String keyStr, String data) throws Exception {
            // 转换密钥
            Key key = new SecretKeySpec(Base64.getDecoder().decode(keyStr), KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            // 解密
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] result = cipher.doFinal(Base64.getDecoder().decode(data));
            return new String(result);
        }
    
    
        /**
         * @desc: 生成AES的秘钥,秘钥进行了Base64编码的字符串
         * @version: v0.0.1
         * @return String 对生成的秘钥进行了Base64编码的字符串
         */
        public static String keyGenerate() throws Exception {
            // 生成密钥
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
            keyGenerator.init(new SecureRandom());
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] keyBytes = secretKey.getEncoded();
            return Base64.getEncoder().encodeToString(keyBytes);
        }
        public static void main(String[] args) throws Exception {
            System.out.println(
                    keyGenerate()
            );
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66

    编写一下加解密接口

    /**
     * 加解密处理接口
     */
    public interface CipherHandler {
    
        /**
         * 加密
         * @param data 需要加密的数据
         * @return 加密结果
         */
       String encrypt(String data) throws Exception;
    
        /**
         * 解密
         * @param data 需要加密的数据
         * @return 解密结果
         */
        String decrypt(String data) throws Exception;
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    public class AEScipher implements CipherHandler{
        private final static String keyStr="glRwFSBcKzppYVQiwT8M/Q==";
    
        @Override
        public String encrypt(String data) throws Exception {
            return AESUtil.encrypt(this.keyStr,data);
        }
    
        @Override
        public String decrypt(String data) throws Exception {
            return AESUtil.decrypt(this.keyStr,data);
        }
    
        public static CipherHandler getAEScipher(){
            return new AEScipher();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    接下来写一下加解密的拦截器

    
    @Intercepts({
            @Signature(type = ParameterHandler.class, method = "setParameters", args = PreparedStatement.class),
    })
    @Component
    @Slf4j
    public class ParameterInterceptor implements Interceptor {
    
        private CipherHandler cipherHandler = AEScipher.getAEScipher();
        @Override
        public Object intercept(Invocation invocation) throws Throwable {
            DefaultParameterHandler parameterHandler = (DefaultParameterHandler) invocation.getTarget();
            // 获取参数对像,即 mapper 中 paramsType 的实例
            Field parameterField = parameterHandler.getClass().getDeclaredField("parameterObject");
            parameterField.setAccessible(true);
            // 取出实例
            Object parameterObject = parameterField.get(parameterHandler);
            try {
                // 搜索该方法中是否有需要加密的字段
                List<Field> fieldList = searchParamAnnotation(parameterHandler);
                //加密
                if(!CommonHelper.isEmpty(fieldList)){
                    dealParamEncrypt(fieldList,parameterObject);
                }
                parameterField.set(parameterHandler, parameterObject);
                PreparedStatement ps = (PreparedStatement) invocation.getArgs()[0];
                parameterHandler.setParameters(ps);
    
            } catch (Exception e) {
                log.info(e.getMessage());
            }
            return invocation.proceed();
        }
    
    
        /**
         * 查找需要需要加密字段
         * @param parameterHandler
         * @return
         * @throws Exception
         */
        private List<Field> searchParamAnnotation(ParameterHandler parameterHandler) throws Exception {
            Class<DefaultParameterHandler> handlerClass = DefaultParameterHandler.class;
            Field mappedStatementFiled = handlerClass.getDeclaredField("mappedStatement");
            mappedStatementFiled.setAccessible(true);
            MappedStatement mappedStatement = (MappedStatement) mappedStatementFiled.get(parameterHandler);
            String methodName = mappedStatement.getId();
            // 获取Mapper类对象
            Class<?> mapperClass = Class.forName(methodName.substring(0, methodName.lastIndexOf('.')));
            methodName = methodName.substring(methodName.lastIndexOf('.') + 1);
            Method[] methods = mapperClass.getDeclaredMethods();
            Method method = null;
            for (Method m : methods) {
                if (m.getName().equals(methodName)) {
                    method = m;
                    break;
                }
            }
            List<Field> fieldList = new ArrayList<>();
            if (method != null) {
                Annotation[][] pa = method.getParameterAnnotations();
                Parameter[] parameters = method.getParameters();
                for (int i = 0; i < pa.length; i++) {
                    Parameter parameter = parameters[i];
                    String typeName = parameter.getParameterizedType().getTypeName();
                    // 去除泛型导致的ClassNotFoundException
                    Class<?> parameterClass = Class.forName(typeName.contains("<") ? typeName.substring(0, typeName.indexOf("<")) : typeName);
                    Field[] declaredFields = parameterClass.getDeclaredFields();
                    for (Field declaredField : declaredFields) {
                        Annotation annotation = declaredField.getAnnotation(Encryption.class);
                        if(!CommonHelper.isEmpty(annotation))fieldList.add(declaredField);
                    }
                }
            }
            return fieldList;
        }
    
        /**
         * 处理加密类
         * @param fields
         * @param parameterObject
         * @throws Exception
         */
        private void dealParamEncrypt(List<Field> fields,Object parameterObject) throws Exception {
            fields.forEach(declaredField->{
                declaredField.setAccessible(true);
                Object o = null;
                try {
                    o = declaredField.get(parameterObject);
                    declaredField.set(parameterObject,cipherHandler.encrypt(o.toString()));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
    
        }
    
        @Override
        public Object plugin(Object target) {
            return Plugin.wrap(target,this);
        }
    
        @Override
        public void setProperties(Properties properties) {
    
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109

    查询结果解密

    
    @Intercepts({
            @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})
    })
    @Component
    public class ResultSetInterceptor implements Interceptor {
    
        private CipherHandler cipherHandler = AEScipher.getAEScipher();
        @Override
        public Object intercept(Invocation invocation) throws Throwable {
            // 取出查询的结果
            Object resultObject = invocation.proceed();
            if (Objects.isNull(resultObject)) {
                return null;
            }
            // 基于selectList
            if (resultObject instanceof List<?>) {
                List<?> resultList = (List<?>) resultObject;
                if (!CommonHelper.isEmpty(resultList)) {
                    for (Object obj : resultList) {
                        toDecrypt(obj);
                    }
                }
            } else {
                toDecrypt(resultObject);
            }
            return resultObject;
        }
    
        private void toDecrypt(Object object) throws Exception {
            Class<?> objectClass = object.getClass();
            Field[] declaredFields = objectClass.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                Annotation annotation = declaredField.getAnnotation(Encryption.class);
                if(!CommonHelper.isEmpty(annotation)){
                    declaredField.setAccessible(true);
                    declaredField.set(object,cipherHandler.decrypt(declaredField.get(object).toString()));
                }
            }
        }
    
        @Override
        public Object plugin(Object o) {
            return Plugin.wrap(o,this);
        }
    
        @Override
        public void setProperties(Properties properties) {
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51

    判空工具类

    public class CommonHelper {
    
        public static boolean isEmpty(Object o){
            if(o==null)return true;
            if(o instanceof String){
              return  ((String) o).isEmpty();
            }else if(o instanceof List){
                return CollectionUtils.isEmpty((List) o) || ((List<?>) o).size()==0 ;
            }else if(o instanceof Map){
                return CollectionUtils.isEmpty((Map) o) || ((Map<?,?>) o).size()==0 ;
            }else {
                return Objects.isNull(o);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    测试结果:
    插入数据
    在这里插入图片描述
    在这里插入图片描述

    查询数据:
    在这里插入图片描述

  • 相关阅读:
    IronPDF v2023.5.8 For .NET Crack
    Multilevel Cooperative Coevolution for Large Scale Optimization
    [论文阅读笔记17]MAT: Motion-Aware Multi-Object Tracking
    [13]javascript的类型检测的方法
    华为ensp创建 VLAN
    leetcode-LCP 06. 拿硬币
    大屏项目开发
    python学习笔记(二)
    通过 MSE 实现基于Apache APISIX的全链路灰度
    【前端设计模式】之解释器模式
  • 原文地址:https://blog.csdn.net/Pluto372/article/details/133844455