利用Mybatis拦截器+反射机制,设计加解密注解

该文章介绍了如何通过Mybatis拦截器和自定义注解,结合反射机制,实现在插入和查询数据库时对特定字段的自动加解密。在拦截器中处理输入参数和输出结果,确保敏感信息的安全。加密和解密方法可以根据需求选择不同的算法实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现方案:

利用Mybatis拦截器+反射机制,设计加解密注解,可以对特定字段入库出库时,实现自动加解密。
①拦截器原理详见Mybatis插件系列一:拦截器的基础知识

在这里插入图片描述

代码实现:

一、创建自定义注解EncryptionAndDecryption

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EncryptionAndDecryption {
    String value() default "";
}

二、实现Mybatis拦截器方法:

@Slf4j
public abstract class EncryptionAndDecryptionPlugin implements Interceptor {
    public EncryptionAndDecryptionPlugin() {
    }
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //log.info("Begin SQL Plugin");
        if (invocation.getArgs() != null && invocation.getArgs().length > 1) {
            MappedStatement statement = (MappedStatement) invocation.getArgs()[0];
            String methodName = invocation.getMethod().getName();
            Object parameter = invocation.getArgs()[1];
            BoundSql sql = statement.getBoundSql(parameter);
            //log.info("sql is {}", sql.getSql());

            // Handle input parameters
            if (parameter != null) {
                List<Field> inputFields = getAnnotationFields(parameter.getClass(), EncryptionAndDecryption.class);
                if (inputFields.size() > 0) {
                    log.info("################ methodName: {}", methodName);
                    if (methodName.equals("query") || methodName.equals("update")) {
                        for (Field field : inputFields) {
                            if (field.getType().equals(String.class)) {
                                field.setAccessible(true);
                                String plaintextValue = (String) field.get(parameter);
                                if (!StringUtil.isEmpty(plaintextValue)) {
                                    String ciphertextValue = encryptInner(plaintextValue, parameter, field.getName());
                                    field.set(parameter, ciphertextValue);
                                }
                            }
                        }
                    }
                }
            }
        }

        Object returnValue = invocation.proceed();

        // if resul data has EncryptionAndDecryption annotation, clear this local cache
        boolean isClearLocalCache = false;

        try {
            //Handle output parameters
            if (returnValue instanceof ArrayList<?>) {
                log.info("################ result-list: {}", ((ArrayList) returnValue).size());
                List<?> list = (ArrayList<?>) returnValue;
                for (Object val : list) {
                    if (val == null) {
                        continue;
                    }
                    List<Field> outputFields = getAnnotationFields(val.getClass(), EncryptionAndDecryption.class);
                    if (outputFields.size() > 0) {
                        isClearLocalCache = true;
                        for (Field field : outputFields) {
                            if (field.getType().equals(String.class)) {
                                field.setAccessible(true);
                                String cipheredValue = (String) field.get(val);
                                if (StringUtils.isNotBlank(cipheredValue)) {
                                    String plaintextValue = decryptInner(cipheredValue, val, field.getName());
                                    field.set(val, plaintextValue);
                                }
                            }
                        }
                    }
                }
            } else {
                log.info("################ result: {}", returnValue);
            }
        } finally {
            if (isClearLocalCache) {
                // clear local cache
                Object target = invocation.getTarget();
                if (target instanceof CachingExecutor) {
                    CachingExecutor executor = (CachingExecutor)target;
                    executor.clearLocalCache();
                }
            }
        }

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

    @Override
    public void setProperties(Properties properties) {

    }

    private List<Field> getAnnotationFields(Class entityCls, Class annotationCls) {
        ArrayList list = new ArrayList();

        try {
            Field[] arr$ = entityCls.getDeclaredFields();
            int len$ = arr$.length;

            for(int i$ = 0; i$ < len$; ++i$) {
                Field field = arr$[i$];
                if (field.isAnnotationPresent(annotationCls)) {
                    try {
                        list.add(field);
                    } catch (Throwable var9) {
                        log.error("################ CheckAnnotation failed!",var9);
                    }
                }
            }
        } catch (SecurityException var10) {
            log.error("################ CheckAnnotation failed!",var10);
        }

        return list;
    }

    protected abstract String encryptInner(String plaintext, Object entityObj, String attributeName);

    protected abstract String decryptInner(String cipheredValue, Object entityObj, String attributeName);
}

三、实现自定义加解密方法,也可以自由选择国密算法:

@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})
})
@Component
@Slf4j
public class MyPlugin extends EncryptionAndDecryptionPlugin {
    @Resource
    private DeviceCryptoService deviceCryptoService;
    /**
     * 密钥别名
     */
    @Value("${wyaks.aksAliasName}")
    private String aliasName;

    @Override
    protected String encryptInner(String plaintext, Object entityObj, String attributeName) {
        log.info("encryptInner begin,attributeName:" + attributeName);
        if (StringUtils.isBlank(plaintext)) {
            log.info("encryptInner empty,attributeName:" + attributeName);
            return plaintext;
        }
        return encrypt(plaintext);
    }

    @Override
    protected String decryptInner(String cipheredValue, Object entityObj, String attributeName) {
        log.info("decryptInner begin,attributeName:" + attributeName);
        if (StringUtils.isBlank(cipheredValue)) {
            log.info("decryptInner empty,attributeName:" + attributeName);
            return cipheredValue;
        }
        return decrypt(cipheredValue);
    }

    public String encrypt(String plaintext) {
        log.info("加密数据:{}", plaintext);
        String encryptData = null;
        try {
            encryptData = deviceCryptoService.encryptString(aliasName, plaintext.getBytes("UTF-8"));
        } catch (Exception e) {
            log.error("加密数据异常:" + e.toString(), e);
            throw new RuntimeException("加密异常");
        }
        log.info("加密数据返回:{}", encryptData);
        return encryptData;
    }

    public String decrypt(String cipheredValue) {
        log.info("解密数据:{}", cipheredValue);
        String decryptData = null;
        try {
            decryptData = new String(deviceCryptoService.decryptString(aliasName, cipheredValue), "UTF-8");
        } catch (Exception e) {
            log.error("解密数据异常:" + e.toString(), e);
            throw new RuntimeException("解密异常");
        }
        log.info("解密数据返回:{}", decryptData);
        return decryptData;
    }
}
MyBatis拦截器和自定义注解MyBatis框架中的两个重要特性。下面我会分别解释它们的作用和用法。 MyBatis拦截器是一种机制,可以在执行SQL语句的过程中对其进行拦截和修改。它提供了一种方便的方式来扩展和自定义MyBatis的功能。拦截器可以在SQL语句执行前后、参数设置前后、结果集处理前后等关键点进行拦截,并对其进行修改或增强。 要实现一个MyBatis拦截器,你需要实现`Interceptor`接口,并重写其中的方法。其中最重要的方法是`intercept`,它接收一个`Invocation`对象作为参数,通过该对象你可以获取到当前执行的SQL语句、参数等信息,并可以对其进行修改。另外还有`plugin`方法和`setProperties`方法用于对拦截器进行初始化。 自定义注解是一种用于标记和配置特定功能的注解。在MyBatis中,你可以使用自定义注解来配置一些特殊的功能,比如动态SQL的条件判断、结果集映射等。通过自定义注解,你可以将一些常用的功能封装成注解,并在需要时直接使用。 要使用自定义注解,你需要先定义一个注解,并在相应的地方使用该注解。然后通过MyBatis的配置文件或者Java代码进行配置,告诉MyBatis如何处理这些注解。在MyBatis的执行过程中,它会根据注解的配置来动态生成相应的SQL语句或者进行特定的处理。 总结一下,MyBatis拦截器和自定义注解MyBatis框架中的两个重要特性。拦截器可以对SQL语句进行拦截和修改,自定义注解可以用于配置一些特殊功能。它们都提供了一种扩展和自定义MyBatis功能的方式。如果你有具体的问题或者需要更详细的示例代码,欢迎继续提问!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值