Implementation method for encrypting and decrypting data based on MyBatis

By using annotations and interceptors to implement data encryption and decryption in the MyBatis framework, the problems of mixed logic and high cost in traditional data encryption methods are solved, flexible and secure data processing solutions are provided, and special scenarios such as fuzzy query are supported.

CN119046961APending Publication Date: 2024-11-29ZHUHAI GOTECH INTELLIGENT TECH CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202411057787.5
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2024-08-02
Publication Date
2024-11-29

AI Technical Summary

Technical Problem

The traditional data encryption method is implemented at the application level, resulting in the mixed encryption and decryption logic and business logic, poor code maintainability and scalability, and does not support special scenarios such as fuzzy queries, which increases development and maintenance costs and lacks general and flexible MyBatis framework integrates data encryption and decryption methods.

Method used

By using @FieldEncrypt annotation in the entity class to identify the fields that need to be encrypted, using @ParamMapEncrypt annotation in the query class to specify the parameters that need to be encrypted, combining with MyBatis interceptor to implement data encryption and decryption, supporting different encryption algorithms, and during the query process, Perform encryption and decryption processing.

Benefits of technology

It realizes the separation of data encryption and decryption and business logic, provides flexible, secure and scalable data encryption and decryption solutions, supports fuzzy queries and conditional queries, and reduces development and maintenance costs.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN119046961A_ABST
    Figure CN119046961A_ABST
Patent Text Reader

Abstract

The invention discloses an implementation method for encrypting and decrypting data based on MyBatis, which comprises the following steps of: S1, adding a FieldEncrypt annotation in an entity class Entity through an annotation module, identifying which fields need to be encrypted and stored, and adding a ParamMap Encrypt annotation in a query class Mapper; according to the functional method for encrypting and decrypting the data based on the mybatis, parameters can be dynamically configured through annotation, seamless integration with a Mybatis framework can be achieved, different encryption and decryption modes can be achieved through a planning mode, the problem of coupling of encryption logic and service logic is thoroughly solved, a more flexible, safer and extensible data encryption and decryption scheme is provided, and the data encryption and decryption efficiency is improved. Meanwhile, conditional query can be carried out on the encrypted and stored data, and different requirements for result data are met.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention relates to the technical field of data encryption and decryption, and in particular to a method for implementing data encryption and decryption based on MyBatis. Background Art

[0002] As information security issues are increasingly valued, data encryption plays an increasingly important role in various application systems to prevent data from being stolen or used maliciously. Especially for some systems involving sensitive information, such as campus, finance, medical and other fields, the demand for data encryption is more urgent. Traditional data encryption methods are usually implemented at the application level, and the encryption and decryption logic is usually mixed with the business logic, resulting in poor code maintainability and scalability; the implementation method based on database views or functions may not support special scenarios such as fuzzy queries; different business modules or application systems need to repeatedly implement similar encryption and decryption logic, which increases development and maintenance costs. In Spring Boot projects, it is a common practice to implement data addition, deletion, modification and query based on the MyBatis framework, but there is currently no more common or flexible way to integrate data encryption and decryption based on the MyBatis framework. For this reason, we propose a method for implementing data encryption and decryption based on MyBatis. Summary of the invention

[0003] Based on the technical problems existing in the background technology, the present invention proposes a method for implementing data encryption and decryption based on MyBatis.

[0004] The present invention proposes a method for implementing data encryption and decryption based on MyBatis, comprising the following steps: S1: Add the @FieldEncrypt annotation to the entity class Entity through the annotation module to identify which fields need to be encrypted and stored in the database, and add the @ParamMapEncrypt annotation to the query class Mapper, and write the fields that need to be encrypted before querying in the encryptParamNames attribute for data filtering; S2: Set the configuration loading class through the configuration module, start the encryption and decryption switch, configure the encryption and decryption algorithm and key, configure the MyBatis encryption interceptor FieldEncryptInterceptor and the decryption interceptor FieldDecryptInterceptor; S3: Start the program through the main program, and the MyBatis encryption interceptor FieldEncryptInterceptor and decryption interceptor FieldDecryptInterceptor are loaded; S4: The main program executes the insert / update method of MyBatis. The MyBatis interceptor module listens and intercepts the insert / update method through the MyBatis encryption interceptor FieldEncryptInterceptor loaded in S3. At the same time, in the Intercept method, the main program traverses and scans all fields in the class to find the fields with @FieldEncrypt annotations that need to be encrypted; S5: Encrypt the fields that need to be encrypted in S4 using the encryption and decryption module according to the configured algorithm and key; S6: Execute the SQL insert / update command to store the encrypted data securely in the database; S7: At the same time, the main program executes the query method of MyBatis, and listens to and intercepts the query method through the MyBatis encryption interceptor FieldEncryptInterceptor loaded in S3. In the Intercept method, all Mapper classes are traversed and scanned to find the annotated method with @ParamMapEncrypt; S8: Encrypt the parameter list encryptParamNames annotated in S7 that needs to be encrypted; S9: Execute the sql select command, filter the data according to the parameter conditions, obtain the result set, and intercept and monitor the result set data through the decryption interceptor FieldDecryptInterceptor. In the Intercept method, the result set fields are traversed, and the fields annotated with @FieldEncrypt are decrypted through the encryption and decryption module; S10: Set the data decrypted in S9 into the returned result data.

[0005] Preferably, in S1, the annotation module is used to mark custom annotations for fields that need to be encrypted and decrypted. @FieldEncrypt is used to encrypt or decrypt data when operating data; @ParamMapEncrypt is used to query data, specify a parameter list, encrypt the parameters and then query the data. Developers only need to use the annotation on the corresponding fields or methods.

[0006] Preferably, in the S4, the MyBatis interceptor module is the key to integration with the MyBatis framework, and a custom Interceptor is used to implement data encryption and decryption, intercept the execution process of MyBatis, and realize automatic encryption and storage in persistence operations; in ordinary queries or special query scenarios such as fuzzy queries and associated queries, the MyBatis interceptor module will encrypt the query conditions and decrypt the result sets to ensure the correctness and security of the query results.

[0007] Preferably, in S5, the encryption and decryption module defines an abstract interface through a strategy mode, and can flexibly implement multiple encryption algorithms, such as SM4 (national encryption), AES, DES, or a custom encryption module, etc. It performs encryption and decryption operations of different encryption algorithms on fields or methods marked with @FieldEncrypt and @ParamMapEncrypt annotations according to the configuration information provided by the configuration module.

[0008] Preferably, in S2, the configuration module provides flexible configuration of whether to start the encryption and decryption mechanism, encryption and decryption algorithm, encryption and decryption key and MyBatis interceptor and other mechanisms. The configuration module will parse the relevant configuration, provide the information to the encryption and decryption module, and start the MyBatis interceptor module for monitoring.

[0009] Preferably, in S1, the code program used by the annotation module when performing annotation is as follows: @Data @Entity @Table(name = "app_user") @TableName(value = "app_user") @NoArgsConstructor public class AppUserBean implements Serializable { @Column(name = "password") @FieldEncrypt private String password; / / Login password @Column(name = "userid") @FieldEncrypt private String userid; / / Business number @Column(name = "name") private String name; / / User name, equivalent to nickname @Column(name = "mobile_userid") @FieldEncrypt private String mobileUserid; / / mobile phone account userid } @Mapper public interface AppUserDao extends BaseMapper <appuserbean>{ / / Mark query parameters that need to be encrypted before querying @ParamMapEncrypt(encryptParamNames = {"userid", "mobile"}) List <appuserbean>findAppUser(Map<String, Object> map); }.

[0010] Preferably, in S2, the configuration module uses the following program code when performing configuration: import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.StrUtil; import lombok.extern.slf4j.Slf4j; import org.mybatis.spring.mapper.MapperFactoryBean; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.core.env.Environment; import org.springframework.lang.NonNull; import java.lang.reflect.Method; import java.util.TreeMap; @Lazy @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = "mybatis.encryptor",name = {"enabled"},havingValue = "true") @Slf4j public class EncryptAutoconfiguration implements BeanPostProcessor { @javax.annotation.Resource AbstractApplicationContext applicationContext; @Bean @ConditionalOnMissingBean public PropertyContext propertyContext(Environment environment) { return ScanEntityClassConfiguration.propertyContext(environment); } @Bean @ConditionalOnMissingBean public FieldEncryptInterceptor fieldEncryptInterceptor(@Autowired(required = false) IEncryptor encryptor, PropertyContext propertyContext) { if (encryptor == null) { encryptor = new DefaultEncryptor(); applicationContext.getBeanFactory().registerSingleton("defaultEncryptor", encryptor); } return new FieldEncryptInterceptor(encryptor, propertyContext); } @Bean @ConditionalOnMissingBean public FieldDecryptInterceptor fieldDecryptInterceptor(@Autowired(required = false) IEncryptor encryptor, PropertyContext propertyContext) { if (encryptor == null) { encryptor = new DefaultEncryptor(); applicationContext.getBeanFactory().registerSingleton("defaultEncryptor", encryptor); } return new FieldDecryptInterceptor(encryptor, propertyContext); } @Override public Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException { if (bean instanceof MapperFactoryBean) { Class<?> mapperInterface = ((MapperFactoryBean<?>) bean).getMapperInterface(); Method[] methods = ReflectUtil.getMethods(mapperInterface, method -> method.getAnnotation(ParamMapEncrypt.class) !=null); String className = mapperInterface.getName(); for (Method method : methods) { ParamMapEncrypt queryParamEncrypt =method.getAnnotation(ParamMapEncrypt.class); String statementId = className + StrUtil.DOT + method.getName(); TreeMap<String, Object> queryParamNames = new TreeMap<>(); for (String name : queryParamEncrypt.encryptParamNames()) { queryParamNames.put(name, null); } applicationContext.getBean(PropertyContext.class).addStatementProperty(statementId, new QueryParamProperty(queryParamNames,mapperInterface)); } } return BeanPostProcessor.super.postProcessBeforeInitialization(bean,beanName); } }.

[0011] Preferably, in S4, the program code used by the MyBatis encryption interceptor FieldEncryptInterceptor when intercepting and monitoring is as follows: import lombok.extern.slf4j.Slf4j; 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.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.Plugin; import org.apache.ibatis.plugin.Signature; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import java.util.HashMap; import java.util.Map; import java.util.Properties; / ** * Encryption interceptor * / @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, CacheKey.class, BoundSql.class}) }) @Slf4j public class FieldEncryptInterceptor implements Interceptor { IEncryptor encryptor; PropertyContext propertyContext; Map<SqlCommandType, AbstractEncryptHandleStrategy> encryptHandleStrategyMap = new HashMap<>(); public FieldEncryptInterceptor(IEncryptor encryptor, PropertyContextpropertyContext) { this.propertyContext = propertyContext; this.encryptor = encryptor; encryptHandleStrategyMap.put(SqlCommandType.SELECT, newQueryHandleStrategy(encryptor, propertyContext)); encryptHandleStrategyMap.put(SqlCommandType.UPDATE, newUpdateHandleStrategy(encryptor, propertyContext)); encryptHandleStrategyMap.put(SqlCommandType.INSERT, newInsertHandleStrategy(encryptor, propertyContext)); } @Override public Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs(); MappedStatement mappedStatement = (MappedStatement) args[0]; Configuration configuration = mappedStatement.getConfiguration(); AbstractEncryptHandleStrategy strategy = encryptHandleStrategyMap.get(mappedStatement.getSqlCommandType()); if (strategy != null) { strategy.handel(args, mappedStatement, configuration); } return invocation.proceed(); } @Override public Object plugin(Object target) { return target instanceof Executor ? Plugin.wrap(target, this): target; } @Override public void setProperties(Properties properties) { Interceptor.super.setProperties(properties); } }.

[0012] Preferably, in S9, when the decryption interceptor FieldDecryptInterceptor performs monitoring interception, the program code used is as follows: import lombok.extern.slf4j.Slf4j; 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.mapping.ResultMapping; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.session.Configuration; import java.lang.reflect.Field; import java.sql.Statement; import java.util.List; import java.util.Properties; import java.util.function.BiConsumer; import java.util.stream.Collectors; / ** * Decryption interceptor * / @Intercepts({@Signature( type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class} )}) @Slf4j public class FieldDecryptInterceptor implements Interceptor { IEncryptor encryptor; PropertyContext propertyContext; public FieldDecryptInterceptor(IEncryptor encryptor,PropertyContext propertyContext) { this.propertyContext = propertyContext; this.encryptor = encryptor; } @Override public Object intercept(Invocation invocation) throws Throwable { List<?> result = (List<?>) invocation.proceed(); Object target = invocation.getTarget(); if (target instanceof DefaultResultSetHandler) { DefaultResultSetHandler defaultResultSetHandler =(DefaultResultSetHandler) target; Field mappedStatementField = defaultResultSetHandler.getClass().getDeclaredField("mappedStatement"); mappedStatementField.setAccessible(true); MappedStatement mappedStatement = (MappedStatement)mappedStatementField.get(defaultResultSetHandler); for (Object next : result) { if (null != next && !this.handlerResult(mappedStatement, next, this::decrypt)) { break; } } } return result; } @Override public Object plugin(Object target) { return target instanceof ResultSetHandler ? Plugin.wrap(target, this) : target; } @Override public void setProperties(Properties properties) { Interceptor.super.setProperties(properties); } private boolean handlerResult(MappedStatement mappedStatement,Object obj, BiConsumer<Object, FieldSetProperty> decryptConsumer) { Configuration configuration = mappedStatement.getConfiguration(); final MetaObject metaObject = configuration.newMetaObject(obj); this.doDecryptOrVerify(metaObject, obj.getClass(),decryptConsumer); / / JOIN MAPPING List <resultmapping>mappings = null; if (mappedStatement.hasNestedResultMaps()) { final ResultMap resultMap = mappedStatement.getResultMaps().isEmpty() ? null : mappedStatement.getResultMaps().get(0); if (resultMap != null) { mappings = resultMap.getResultMappings().stream().filter(mapping -> mapping.getNestedResultMapId() != null).collect(Collectors.toList()); } } if (mappings == null || mappings.isEmpty()) { return true; } for (ResultMapping mapping : mappings) { String nestedResultProperty = mapping.getProperty(); Object nestedResult = metaObject.getValue(nestedResultProperty); if (nestedResult instanceof List) { List<?> nestedResultList = (List<?>) nestedResult; for (Object result : nestedResultList) { this.doDecryptOrVerify(result, result.getClass(),decryptConsumer); } } else { Class<?> nestedResultClass = mapping.getJavaType(); this.doDecryptOrVerify(nestedResult,nestedResultClass, decryptConsumer); } metaObject.setValue(nestedResultProperty, nestedResult); } return true; } private void doDecryptOrVerify(Object result, Class<?> beanClass,BiConsumer<Object, FieldSetProperty> decryptConsumer) { / / DECRYPT List <fieldsetproperty>fieldSetProperties = propertyContext.getFieldSetProperty(beanClass); if (fieldSetProperties != null && !fieldSetProperties.isEmpty()) { fieldSetProperties.parallelStream().forEach((fieldSetProperty) -> decryptConsumer.accept(result, fieldSetProperty)); } } private void decrypt(Object source, FieldSetPropertyfieldSetProperty) { String fieldName = fieldSetProperty.getFieldName(); Object value = MetaObjectUtils.getValue(source, fieldName); if (null != value) { if (null != encryptor && value instanceof String) { try { FieldEncrypt fieldEncrypt = fieldSetProperty.getFieldEncrypt(); if (null != fieldEncrypt) { value = encryptor.decrypt((String) value); } } catch (Exception e) { log.warn("field decrypt error : {}",e.getMessage()); } } MetaObjectUtils.setValue(source, fieldName, value); } } }.

[0013] Compared with the prior art, the present invention has the following beneficial effects: The functional method for data encryption and decryption based on mybatis proposed in the present invention can dynamically configure parameters through annotations and seamlessly integrate with the MyBatis framework, and can realize different encryption and decryption methods through planning modes, which completely solves the problem of coupling encryption logic with business logic, and provides a more flexible, secure and scalable data encryption and decryption solution. At the same time, it can realize conditional query of data that has been encrypted and stored in the warehouse to meet different requirements for result data. BRIEF DESCRIPTION OF THE DRAWINGS

[0014] Figure 1 The present invention provides a flowchart of a method for implementing data encryption and decryption based on MyBatis. DETAILED DESCRIPTION

[0015] The present invention will be further explained below in conjunction with specific embodiments. Example

[0016] Reference Figure 1 This embodiment proposes a method for implementing data encryption and decryption based on MyBatis, including the following steps: S1: Add the @FieldEncrypt annotation to the entity class Entity through the annotation module to identify which fields need to be encrypted and stored in the database, and add the @ParamMapEncrypt annotation to the query class Mapper. Write the fields that need to be encrypted before querying in the encryptParamNames attribute for data filtering. The annotation module is used to mark custom annotations for fields that need to be encrypted and decrypted. @FieldEncrypt is used to encrypt or decrypt data when operating data; @ParamMapEncrypt is used to query data, specify a parameter list, and encrypt the parameters before querying the data. Developers only need to use the annotation on the corresponding fields or methods. The code program used by the annotation module when annotating is as follows: @Data @Entity @Table(name = "app_user") @TableName(value = "app_user") @NoArgsConstructor public class AppUserBean implements Serializable { @Column(name = "password") @FieldEncrypt private String password; / / Login password @Column(name = "userid") @FieldEncrypt private String userid; / / Business number @Column(name = "name") private String name; / / User name, equivalent to nickname @Column(name = "mobile_userid") @FieldEncrypt private String mobileUserid; / / mobile phone account userid } @Mapper public interface AppUserDao extends BaseMapper <appuserbean>{ / / Mark query parameters that need to be encrypted before querying @ParamMapEncrypt(encryptParamNames = {"userid", "mobile"}) List <appuserbean>findAppUser(Map<String, Object> map); }; S2: Set the configuration loading class through the configuration module, start the encryption and decryption switch, configure the encryption and decryption algorithm and key, configure the MyBatis encryption interceptor FieldEncryptInterceptor and the decryption interceptor FieldDecryptInterceptor; The configuration module provides flexible configuration of whether to start the encryption and decryption mechanism, encryption and decryption algorithm, encryption and decryption key and MyBatis interceptor. The configuration module will parse the relevant configuration, provide the information to the encryption and decryption module, and start the MyBatis interceptor module for monitoring; When configuring the configuration module, the program code used is as follows: import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.StrUtil; import lombok.extern.slf4j.Slf4j; import org.mybatis.spring.mapper.MapperFactoryBean; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.core.env.Environment; import org.springframework.lang.NonNull; import java.lang.reflect.Method; import java.util.TreeMap; @Lazy @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = "mybatis.encryptor",name = {"enabled"},havingValue = "true") @Slf4j public class EncryptAutoconfiguration implements BeanPostProcessor { @javax.annotation.Resource AbstractApplicationContext applicationContext; @Bean @ConditionalOnMissingBean public PropertyContext propertyContext(Environment environment) { return ScanEntityClassConfiguration.propertyContext(environment); } @Bean @ConditionalOnMissingBean public FieldEncryptInterceptor fieldEncryptInterceptor(@Autowired(required = false) IEncryptor encryptor, PropertyContext propertyContext) { if (encryptor == null) { encryptor = new DefaultEncryptor(); applicationContext.getBeanFactory().registerSingleton("defaultEncryptor", encryptor); } return new FieldEncryptInterceptor(encryptor, propertyContext); } @Bean @ConditionalOnMissingBean public FieldDecryptInterceptor fieldDecryptInterceptor(@Autowired(required = false) IEncryptor encryptor, PropertyContext propertyContext) { if (encryptor == null) { encryptor = new DefaultEncryptor(); applicationContext.getBeanFactory().registerSingleton("defaultEncryptor", encryptor); } return new FieldDecryptInterceptor(encryptor, propertyContext); } @Override public Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException { if (bean instanceof MapperFactoryBean) { Class<?> mapperInterface = ((MapperFactoryBean<?>) bean).getMapperInterface(); Method[] methods = ReflectUtil.getMethods(mapperInterface, method -> method.getAnnotation(ParamMapEncrypt.class) !=null); String className = mapperInterface.getName(); for (Method method : methods) { ParamMapEncrypt queryParamEncrypt =method.getAnnotation(ParamMapEncrypt.class); String statementId = className + StrUtil.DOT + method.getName(); TreeMap<String, Object> queryParamNames = new TreeMap<>(); for (String name : queryParamEncrypt.encryptParamNames()) { queryParamNames.put(name, null); } applicationContext.getBean(PropertyContext.class).addStatementProperty(statementId, new QueryParamProperty(queryParamNames,mapperInterface)); } } return BeanPostProcessor.super.postProcessBeforeInitialization(bean,beanName); } }; S3: Start the program through the main program, and the MyBatis encryption interceptor FieldEncryptInterceptor and decryption interceptor FieldDecryptInterceptor are loaded; S4: The main program executes the insert / update method of MyBatis. The MyBatis interceptor module listens and intercepts the insert / update method through the MyBatis encryption interceptor FieldEncryptInterceptor loaded in S3. At the same time, in the Intercept method, the main program traverses and scans all fields in the class to find the fields with @FieldEncrypt annotations that need to be encrypted; The MyBatis interceptor module is the key to integration with the MyBatis framework. It customizes the Interceptor for data encryption and decryption, intercepts the execution process of MyBatis, and implements automatic encryption and storage in persistence operations. In ordinary queries or special query scenarios such as fuzzy queries and associated queries, the MyBatis interceptor module encrypts the query conditions and decrypts the result sets to ensure the correctness and security of the query results. The program code used by MyBatis encryption interceptor FieldEncryptInterceptor when intercepting and monitoring is as follows: import lombok.extern.slf4j.Slf4j; 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.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.Plugin; import org.apache.ibatis.plugin.Signature; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import java.util.HashMap; import java.util.Map; import java.util.Properties; / ** * Encryption interceptor * / @Intercepts({ @Signature(type = Executor.class, Method = "update", args = {MappedStatement.class, Object.class}), @Signature(Type = Executor.class, method = "query", It should be noted that there is a syntax error in the original text at "@Signature(Type = Executor.class,method = "query"," where the double quotes are not properly escaped. The above translation is based on the original text as provided. args = {MappedStatement.class, Object.class, RowBounds.class,ResultHandler.class, CacheKey.class, BoundSql.class}) }) @Slf4j public class FieldEncryptInterceptor implements Interceptor { IEncryptor encryptor; PropertyContext propertyContext; Map<SqlCommandType, AbstractEncryptHandleStrategy>encryptHandleStrategyMap = new HashMap<>(); public FieldEncryptInterceptor(IEncryptor encryptor, PropertyContextpropertyContext) { this.propertyContext = propertyContext; this.encryptor = encryptor; encryptHandleStrategyMap.put(SqlCommandType.SELECT, newQueryHandleStrategy(encryptor, propertyContext)); encryptHandleStrategyMap.put(SqlCommandType.UPDATE, newUpdateHandleStrategy(encryptor, propertyContext)); encryptHandleStrategyMap.put(SqlCommandType.INSERT, newInsertHandleStrategy(encryptor, propertyContext)); } @Override public Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs(); MappedStatement mappedStatement = (MappedStatement) args[0]; Configuration configuration = mappedStatement.getConfiguration(); AbstractEncryptHandleStrategy strategy = encryptHandleStrategyMap.get(mappedStatement.getSqlCommandType()); if (strategy != null) { strategy.handel(args, mappedStatement, configuration); } return invocation.proceed(); } @Override public Object plugin(Object target) { return target instanceof Executor ? Plugin.wrap(target, this): target; } @Override public void setProperties(Properties properties) { Interceptor.super.setProperties(properties); } }; S5: Encrypt the fields that need to be encrypted in S4 using the encryption and decryption module according to the configured algorithm and key. The encryption and decryption module defines an abstract interface through the strategy mode, which can flexibly implement multiple encryption algorithms, such as SM4 (national encryption), AES, DES, or custom encryption modules. It performs encryption and decryption operations of different encryption algorithms on fields or methods marked with @FieldEncrypt and @ParamMapEncrypt annotations according to the configuration information provided by the configuration module; S6: Execute the SQL insert / update command to store the encrypted data securely in the database; S7: At the same time, the main program executes the query method of MyBatis, and listens to and intercepts the query method through the MyBatis encryption interceptor FieldEncryptInterceptor loaded in S3. In the Intercept method, all Mapper classes are traversed and scanned to find the annotated method with @ParamMapEncrypt; S8: Encrypt the parameter list encryptParamNames annotated in S7 that needs to be encrypted; S9: Execute the sql select command, filter the data according to the parameter conditions, obtain the result set, and intercept and monitor the result set data through the decryption interceptor FieldDecryptInterceptor. In the Intercept method, the result set fields are traversed, and the fields annotated with @FieldEncrypt are decrypted through the encryption and decryption module; When the decryption interceptor FieldDecryptInterceptor performs monitoring interception, the program code used is as follows: import lombok.extern.slf4j.Slf4j; 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.mapping.ResultMapping; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.session.Configuration; import java.lang.reflect.Field; import java.sql.Statement; import java.util.List; import java.util.Properties; import java.util.function.BiConsumer; import java.util.stream.Collectors; / ** * Decryption interceptor * / @Intercepts({@Signature( type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class} )}) @Slf4j public class FieldDecryptInterceptor implements Interceptor { IEncryptor encryptor; PropertyContext propertyContext; public FieldDecryptInterceptor(IEncryptor encryptor,PropertyContext propertyContext) { this.propertyContext = propertyContext; this.encryptor = encryptor; } @Override public Object intercept(Invocation invocation) throws Throwable { List<?> result = (List<?>) invocation.proceed(); Object target = invocation.getTarget(); if (target instanceof DefaultResultSetHandler) { DefaultResultSetHandler defaultResultSetHandler =(DefaultResultSetHandler) target; Field mappedStatementField = defaultResultSetHandler.getClass().getDeclaredField("mappedStatement"); mappedStatementField.setAccessible(true); MappedStatement mappedStatement = (MappedStatement)mappedStatementField.get(defaultResultSetHandler); for (Object next : result) { if (null != next && !this.handlerResult(mappedStatement, next, this::decrypt)) { break; } } } return result; } @Override public Object plugin(Object target) { return target instanceof ResultSetHandler ? Plugin.wrap(target, this) : target; } @Override public void setProperties(Properties properties) { Interceptor.super.setProperties(properties); } private boolean handlerResult(MappedStatement mappedStatement,Object obj, BiConsumer<Object, FieldSetProperty> decryptConsumer) { Configuration configuration = mappedStatement.getConfiguration(); final MetaObject metaObject = configuration.newMetaObject(obj); this.doDecryptOrVerify(metaObject, obj.getClass(),decryptConsumer); / / JOIN MAPPING List <resultmapping>mappings = null; if (mappedStatement.hasNestedResultMaps()) { final ResultMap resultMap = mappedStatement.getResultMaps().isEmpty() ? null : mappedStatement.getResultMaps().get(0); if (resultMap != null) { mappings = resultMap.getResultMappings().stream().filter(mapping -> mapping.getNestedResultMapId() != null).collect(Collectors.toList()); } } if (mappings == null || mappings.isEmpty()) { return true; } for (ResultMapping mapping : mappings) { String nestedResultProperty = mapping.getProperty(); Object nestedResult = metaObject.getValue(nestedResultProperty); if (nestedResult instanceof List) { List<?> nestedResultList = (List<?>) nestedResult; for (Object result : nestedResultList) { this.doDecryptOrVerify(result, result.getClass(),decryptConsumer); } } else { Class<?> nestedResultClass = mapping.getJavaType(); this.doDecryptOrVerify(nestedResult,nestedResultClass, decryptConsumer); } metaObject.setValue(nestedResultProperty, nestedResult); } return true; } private void doDecryptOrVerify(Object result, Class<?> beanClass,BiConsumer<Object, FieldSetProperty> decryptConsumer) { / / DECRYPT List <fieldsetproperty>fieldSetProperties = propertyContext.getFieldSetProperty(beanClass); if (fieldSetProperties != null && !fieldSetProperties.isEmpty()) { fieldSetProperties.parallelStream().forEach((fieldSetProperty) -> decryptConsumer.accept(result, fieldSetProperty)); } } private void decrypt(Object source, FieldSetPropertyfieldSetProperty) { String fieldName = fieldSetProperty.getFieldName(); Object value = MetaObjectUtils.getValue(source, fieldName); if (null != value) { if (null != encryptor && value instanceof String) { try { FieldEncrypt fieldEncrypt = fieldSetProperty.getFieldEncrypt(); if (null != fieldEncrypt) { value = encryptor.decrypt((String) value); } } catch (Exception e) { log.warn("field decrypt error : {}",e.getMessage()); } } MetaObjectUtils.setValue(source, fieldName, value); } } }; S10: Set the decrypted data in S9 to the returned result data; The functional method for data encryption and decryption based on mybatis proposed in this embodiment can dynamically configure parameters through annotations and seamlessly integrate with the MyBatis framework. Different encryption and decryption methods can be implemented through planning modes, which completely solves the problem of coupling encryption logic with business logic, and provides a more flexible, secure and scalable data encryption and decryption solution. At the same time, conditional queries can be performed on data that has been encrypted and stored in the warehouse to meet different requirements for result data.

[0017] The above description is only a preferred specific implementation manner of the present invention, but the protection scope of the present invention is not limited thereto. Any technician familiar with the technical field can make equivalent replacements or changes according to the technical scheme and inventive concept of the present invention within the technical scope disclosed by the present invention, which should be covered by the protection scope of the present invention.< / fieldsetproperty> < / resultmapping> < / appuserbean> < / appuserbean> < / fieldsetproperty> < / resultmapping> < / appuserbean> < / appuserbean>

Claims

1. A method for implementing data encryption and decryption based on MyBatis, characterized in that: The following steps are involved: S1: Add the @FieldEncrypt annotation to the entity class Entity through the annotation module to identify which fields need to be encrypted and stored in the database, and add the @ParamMapEncrypt annotation to the query class Mapper, and write the fields that need to be encrypted before querying in the encryptParamNames attribute for data filtering; S2: Set the configuration loading class through the configuration module, start the encryption and decryption switch, configure the encryption and decryption algorithm and key, configure the MyBatis encryption interceptor FieldEncryptInterceptor and the decryption interceptor FieldDecryptInterceptor; S3: Start the program through the main program, and the MyBatis encryption interceptor FieldEncryptInterceptor and decryption interceptor FieldDecryptInterceptor are loaded; S4: The main program executes the insert / update method of MyBatis. The MyBatis interceptor module listens and intercepts the insert / update method through the MyBatis encryption interceptor FieldEncryptInterceptor loaded in S3. At the same time, in the Intercept method, the main program traverses and scans all fields in the class to find the fields with @FieldEncrypt annotations that need to be encrypted; S5: Encrypt the fields that need to be encrypted in S4 using the encryption and decryption module according to the configured algorithm and key; S6: Execute the SQL insert / update command to store the encrypted data securely in the database; S7: At the same time, the main program executes the query method of MyBatis, and listens to and intercepts the query method through the MyBatis encryption interceptor FieldEncryptInterceptor loaded in S3. In the Intercept method, all Mapper classes are traversed and scanned to find the annotated method with @ParamMapEncrypt; S8: Encrypt the parameter list encryptParamNames annotated in S7 that needs to be encrypted; S9: Execute the sql select command, filter the data according to the parameter conditions, obtain the result set, and intercept and monitor the result set data through the decryption interceptor FieldDecryptInterceptor. In the Intercept method, the result set fields are traversed, and the fields annotated with @FieldEncrypt are decrypted through the encryption and decryption module; S10: Set the data decrypted in S9 into the returned result data.

2. According to a method for implementing data encryption and decryption based on MyBatis according to claim 1, it is characterized in that: In S1, the annotation module is used to mark custom annotations for fields that need to be encrypted and decrypted. @FieldEncrypt is used to encrypt or decrypt data when operating data; @ParamMapEncrypt is used to query data, specify a parameter list, encrypt the parameters, and then query the data. Developers only need to use the annotation on the corresponding fields or methods.

3. According to a method for implementing data encryption and decryption based on MyBatis according to claim 1, it is characterized in that: In the S4, the MyBatis interceptor module is the key to integration with the MyBatis framework. The custom interceptor implements data encryption and decryption, intercepts the execution process of MyBatis, and realizes automatic encryption and storage in persistence operations. In ordinary queries or fuzzy queries, related queries and special query scenarios, the MyBatis interceptor module will encrypt the query conditions and decrypt the result sets to ensure the correctness and security of the query results.

4. According to a method for implementing data encryption and decryption based on MyBatis according to claim 1, it is characterized in that: In S5, the encryption and decryption module defines an abstract interface through the strategy mode, which can flexibly implement multiple encryption algorithms. It performs encryption and decryption operations of different encryption algorithms on fields or methods marked with @FieldEncrypt and @ParamMapEncrypt annotations according to the configuration information provided by the configuration module.

5. According to a method for implementing data encryption and decryption based on MyBatis according to claim 1, it is characterized in that: In S2, the configuration module provides flexible configuration of whether to start the encryption and decryption mechanism, encryption and decryption algorithm, encryption and decryption key and MyBatis interceptor mechanism. The configuration module will parse the relevant configuration, provide the information to the encryption and decryption module, and start the MyBatis interceptor module for monitoring.