MyBatis-Plus实现部分字段存取加解密

前言

网上教程大致有两种
1.基于MyBatis-Plus自定义类型处理器(TypeHandler)的方法
2.基于MyBatis的方法(拦截器)
这里使用的第二种,为了保护隐私,这里把package路径删掉了

添加两个自定义注解

import java.lang.annotation.*;

/**
 * 字段加解密注解
 * 放到实体类上
 */
@Documented
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CiphertextData {
}
import java.lang.annotation.*;

/**
 * 字段加解密注解
 * 放到需要加解密的字段上
 */
@Documented
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CiphertextField {
}

工具类

MissCipher

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//


import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;

public class MissCipher {
    public MissCipher() {
    }

    public static byte[] work(byte[] content, Key key, byte[] iv, int mode, String algorithm) {
        byte[] result = null;

        try {
            Cipher cipher;
            if (iv == null) {
                if ("RSA".equals(algorithm)) {
                    cipher = Cipher.getInstance(algorithm);
                } else {
                    cipher = Cipher.getInstance(algorithm + "/" + "ECB" + "/" + "PKCS5Padding");
                }

                cipher.init(mode, key);
            } else {
                cipher = Cipher.getInstance(algorithm + "/" + "CBC" + "/" + "PKCS5Padding");
                IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
                cipher.init(mode, key, ivParameterSpec);
            }

            result = cipher.doFinal(content);
        } catch (Exception var8) {
            var8.printStackTrace();
        }

        return result;
    }
}

Des3Utils

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//


import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

public class Des3Utils {
    private static final Encoder ENCODER = Base64.getEncoder();
    private static final Decoder DECODER = Base64.getDecoder();

    public Des3Utils() {
    }

    public static String encrypt(String content, String key) {
        byte[] result = encrypt(content.getBytes(), key.getBytes());
        return ENCODER.encodeToString(result);
    }

    public static byte[] encrypt(byte[] content, byte[] key) {
        return work(content, key, 1);
    }

    public static String encrypt(String content, String key, String iv) {
        byte[] result = encrypt(content.getBytes(), key.getBytes(), iv.getBytes());
        return ENCODER.encodeToString(result);
    }

    public static byte[] encrypt(byte[] content, byte[] key, byte[] iv) {
        return work(content, key, iv, 1);
    }

    public static String decrypt(String content, String key) {
        byte[] result = decrypt(DECODER.decode(content), key.getBytes());
        return new String(result);
    }

    public static byte[] decrypt(byte[] content, byte[] key) {
        return work(content, key, 2);
    }

    public static String decrypt(String content, String key, String iv) {
        byte[] result = decrypt(DECODER.decode(content), key.getBytes(), iv.getBytes());
        return new String(result);
    }

    public static byte[] decrypt(byte[] content, byte[] key, byte[] iv) {
        return work(content, key, iv, 2);
    }

    private static SecretKey generateKey(byte[] key) {
        SecretKey secretKey = null;

        try {
            DESedeKeySpec deSedeKeySpec = new DESedeKeySpec(key);
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DESede");
            secretKey = secretKeyFactory.generateSecret(deSedeKeySpec);
        } catch (Exception var4) {
            var4.printStackTrace();
        }

        return secretKey;
    }

    private static byte[] work(byte[] content, byte[] key, int mode) {
        SecretKey secretKey = generateKey(key);
        return MissCipher.work(content, secretKey, (byte[])null, mode, "DESede");
    }

    private static byte[] work(byte[] content, byte[] key, byte[] iv, int mode) {
        SecretKey secretKey = generateKey(key);
        return MissCipher.work(content, secretKey, iv, mode, "DESede");
    }
}

加解密拦截器

加密拦截器

import com.chinaums.mqy.base.annotation.CiphertextData;
import com.chinaums.mqy.base.annotation.CiphertextField;
import com.chinaums.mqy.util.Des3Utils;
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.*;
import org.apache.shiro.codec.Hex;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Properties;

/**
 * 加密拦截器
 */
@Component
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class ParameterInterceptor implements Interceptor {

    @Resource
    ResultSetInterceptor resultSetInterceptor;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object object = invocation.getArgs()[1];
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        if (SqlCommandType.INSERT.equals(sqlCommandType)) {
//            Object object = invocation.getArgs()[1];
            Class<?> clazz = object.getClass();
            boolean isContain = clazz.isAnnotationPresent(CiphertextData.class);
            if (isContain) {
                Field[] fields = clazz.getDeclaredFields();
                for (Field field : fields) {
                    boolean isContainCiphertextField = field.isAnnotationPresent(CiphertextField.class);
                    if (isContainCiphertextField) {
                        field.setAccessible(true);
                        Object o = field.get(object);
                        if (o != null) {
                            String content = encrypt(String.valueOf(o));
                            field.set(object, content);
                        }
                    }
                }
            }
        } else if ("UPDATE".equals(sqlCommandType.name())) {
//            Object object = invocation.getArgs()[1];
            Class temp = object.getClass();
            boolean res = temp.isAnnotationPresent(CiphertextData.class);
            if (res) {
                Field[] fields = temp.getDeclaredFields();
                for (Field field : fields) {
                    boolean isContainCiphertextField = field.isAnnotationPresent(CiphertextField.class);
                    if (isContainCiphertextField) {
                        field.setAccessible(true);
                        Object o = field.get(object);
                        if (o != null) {
                            String content = encrypt(String.valueOf(o));
                            field.set(object, content);
                        }
                    }
                }
            } else {
                if (object instanceof MapperMethod.ParamMap) {
                    Map map = (Map) object;
                    boolean boll = map.containsKey("param1");
                    Object obj = null;
                    if (boll) {
                        obj = map.get("param1");
                    } else {
                        obj = map.get("et");
                    }
                    Field[] fields = obj.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        boolean isContainCiphertextField = field.isAnnotationPresent(CiphertextField.class);
                        if (isContainCiphertextField) {
                            field.setAccessible(true);
                            Object o = field.get(obj);
                            if (o != null) {
                                String content = encrypt(String.valueOf(o));
                                field.set(obj, content);
                            }
                        }
                    }
                }
            }

        }
        //执行SQL方法
        Object result = invocation.proceed();
        //还原实体类被加密过的字段
        if (object instanceof MapperMethod.ParamMap) {
            Map map = (Map) object;
            if (map.containsKey("param1")) {
                resultSetInterceptor.deal(map.get("param1"));
            } else {
                resultSetInterceptor.deal(map.get("et"));
            }
        } else {
            resultSetInterceptor.deal(invocation.getArgs()[1]);
        }
        return result;
    }


    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

    /**
     * 加密
     *
     * @param content: 待加密的内容
     * @return java.lang.String
     **/
    private String encrypt(String content) {
        byte[] res = Des3Utils.encrypt(content.getBytes(), "EE+oJvs9beODbqQqGZv0GhBP".getBytes(), "00000000".getBytes());
        return Hex.encodeToString(res);
    }
}

解密拦截器

import com.chinaums.mqy.base.annotation.CiphertextData;
import com.chinaums.mqy.base.annotation.CiphertextField;
import com.chinaums.mqy.util.Des3Utils;
import org.apache.ibatis.executor.resultset.DefaultResultSetHandler;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.shiro.codec.Hex;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.List;
import java.util.Objects;
import java.util.Properties;

/**
 * 解密拦截器
 */
@Component
@Intercepts({
        @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = Statement.class)
})
public class ResultSetInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 获取结果集的类型
        DefaultResultSetHandler defaultResultSetHandler = (DefaultResultSetHandler) invocation.getTarget();
        MetaObject metaObject = SystemMetaObject.forObject(defaultResultSetHandler);
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("mappedStatement");
        List<ResultMap> resultMaps = mappedStatement.getResultMaps();
        Class<?> resultType = resultMaps.get(0).getType();
        // 判断是否包含CiphertextData注解
        boolean isContain = resultType.isAnnotationPresent(CiphertextData.class);
        Object resultObject = invocation.proceed();
        if (isContain && !Objects.isNull(resultObject)) {
            List list = (List) resultObject;
            for (Object item : list) {
                this.deal(item);
            }
        }
        return resultObject;
    }

    private boolean validRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return false;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

    /**
     * 处理结果集
     *
     * @param data: 待处理的数据
     **/
    protected void deal(Object data) throws IllegalAccessException {
        Field[] fields = data.getClass().getDeclaredFields();
        for (Field field : fields) {
            boolean isContainCiphertextField = field.isAnnotationPresent(CiphertextField.class);
            if (isContainCiphertextField) {
                field.setAccessible(true);
                Object o = field.get(data);
                if (o != null) {
                    String content = decrypt(String.valueOf(o));
                    field.set(data, content);
                }
            }
        }
    }

    /**
     * 解密
     *
     * @param content: 密文
     * @return java.lang.String
     **/
    private String decrypt(String content) {
        String temp = null;
        try {
            byte[] address = Des3Utils.decrypt(Hex.decode(content), "EE+oJvs9beODbqQqGZv0GhBP".getBytes(), "00000000".getBytes());
            temp = new String(address, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return content;
        }
        return temp;
    }
}

在需要使用的实体类上加注解


大功告成

正常像平常那样使用即可,查出来的结果会自动解密,保存和更新的时候会自动加密,数据库中的是加密的

posted @ 2022-06-17 15:16  DaenMax  阅读(2922)  评论(2编辑  收藏  举报