恿粤晒话大致的实现流程业务层--系统拦截器--数据库--系统拦截器--返回结果加密注解设计把需要加密的字段通过我们自定义的加密注解进行标识所以我们需要先自定义一段加密注解的代码Target(ElementType.FIELD)Retention(RetentionPolicy.RUNTIME)public interface Encrypt {}实体类在实体类上使用注解标记需要加密字段Datapublic class User {private Long id;private String username;Encryptprivate String password;Encryptprivate String email;Encryptprivate String phone;}加密工具类基于AES加密算法实现对字段名的加密大家可以选择其他的加密算法public class EncryptionUtil {privatestaticfinal String ALGORITHM AES;privatestaticfinal String TRANSFORMATION AES/ECB/PKCS5Padding;// AES加密public static String encrypt(String plainText, String key) {try {SecretKeySpec secretKey new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);Cipher cipher Cipher.getInstance(TRANSFORMATION);cipher.init(Cipher.ENCRYPT_MODE, secretKey);byte[] encryptedBytes cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));return Base64.getEncoder().encodeToString(encryptedBytes);} catch (Exception e) {thrownew RuntimeException(加密失败, e);}}// AES解密public static String decrypt(String cipherText, String key) {try {SecretKeySpec secretKey new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);Cipher cipher Cipher.getInstance(TRANSFORMATION);cipher.init(Cipher.DECRYPT_MODE, secretKey);byte[] decryptedBytes cipher.doFinal(Base64.getDecoder().decode(cipherText));returnnew String(decryptedBytes, StandardCharsets.UTF_8);} catch (Exception e) {thrownew RuntimeException(解密失败, e);}}}系统拦截器设计通过拦截实现自动加密和自动解密// 加密拦截器Intercepts({Signature(type Executor.class, method update, args {MappedStatement.class, Object.class})})Componentpublic class FieldEncryptionInterceptor implements Interceptor {Value(${encryption.key:mySecretKey12345})private String encryptionKey;Overridepublic Object intercept(Invocation invocation) throws Throwable {Object[] args invocation.getArgs();MappedStatement mappedStatement (MappedStatement) args[0];Object parameter args[1];// 获取SQL命令类型String sqlCommandType mappedStatement.getSqlCommandType().toString();// 对INSERT和UPDATE操作进行加密处理if (INSERT.equals(sqlCommandType) || UPDATE.equals(sqlCommandType)) {encryptFields(parameter);}return invocation.proceed();}// 解密拦截器Intercepts({Signature(type ResultSetHandler.class, method handleResultSets, args {Statement.class})})Componentpublic class FieldDecryptionInterceptor implements Interceptor {Value(${encryption.key:mySecretKey12345})private String encryptionKey;Overridepublic Object intercept(Invocation invocation) throws Throwable {// 执行原始方法Object result invocation.proceed();// 对查询结果进行解密处理if (result instanceof List) {List list (List) result;for (Object item : list) {decryptFields(item);}} else {decryptFields(result);}return result;}}}测试场景用户信息保护在用户注册时自动加密用户的密码、邮箱、手机号等敏感信息即使数据库泄露也不会造成用户隐私泄露金融数据保护对用户的银行卡号、交易记录等金融数据进行加密存储满足金融行业的合规要求医疗医保数据保护对患者的病历、诊断结果等医疗隐私数据进行加密保护患者隐私企业数据保护对企业内部的商业机密、客户资料等重要数据进行加密保护