在 JPA 实体字段加密中,如何集成 Shiro 加密并支持模糊查询?

解读

面试官想验证三件事:

  1. 你是否真的用过 Shiro 的 CipherService(AesCipherService / BlowfishCipherService),而不是把 Shiro 当“加盐哈希”工具;
  2. 能否把加密/解密动作无缝嵌入 JPA 生命周期(@Converter、@EntityListeners、Hibernate Interceptor),保证对业务代码零侵入;
  3. 面对中文互联网最常见的“手机号/姓名模糊查询”需求,能否给出 国内可落地的方案(前缀索引、明文映射表、布隆过滤器、ES 分词加密索引等),并权衡 合规(《个人信息保护法》)与性能。

知识点

  1. Shiro 对称加密 API:AesCipherService#setKeySize(256)、generateNewKey()、encrypt(text.getBytes(StandardCharsets.UTF_8), key);
  2. JPA 2.1 AttributeConverter 接口:convertToDatabaseColumn / convertToEntityAttribute,配合 @Converter(autoApply=true) 实现字段级透明加密;
  3. JPA 生命周期回调:@PrePersist、@PreUpdate 做“加密”,@PostLoad 做“解密”,可绕过 AttributeConverter 不支持模糊查询的局限;
  4. 国密合规:若项目需过 等保三级 / 密评,必须使用 SM4 算法,此时可继承 Shiro 的 DefaultBlockCipherService 自行实现 Sm4CipherService;
  5. 模糊查询三种国内落地套路:
    • 前缀保留加密(FPE + FF1,仅支持“左匹配 like ‘135%’”);
    • 明文映射表(额外建 phone_plain_hash 列,建 B+Tree 索引,查询时先 hash 再精确匹配,like 则走 ES);
    • Elasticsearch 加密分词索引(把明文同步到 ES,字段用 Shiro 加密存储,查询时用 IK 分词器 + 前缀匹配,ES 集群走国密 TLS)。
  6. 性能与合规权衡:映射表方案在 阿里规约 中被列为“强制”要求敏感字段必须脱敏/加密存储,但映射表需额外 数据访问层权限控制,防止 DBA 直接扫表。

答案

  1. 引入依赖

    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-crypto-cipher</artifactId>
        <version>1.12.0</version>
    </dependency>
    
  2. 封装 Shiro 工具类

    public final class ShiroCrypto {
        private static final AesCipherService CIPHER = new AesCipherService();
        static {
            CIPHER.setKeySize(256);
        }
        private static final byte[] KEY = Base64.decode("你的32位Base64Key");
    
        public static String encrypt(String plain) {
            return Base64.encodeToString(CIPHER.encrypt(plain.getBytes(StandardCharsets.UTF_8), KEY).getBytes());
        }
    
        public static String decrypt(String cipherText) {
            return new String(CIPHER.decrypt(Base64.decode(cipherText), KEY).getBytes(), StandardCharsets.UTF_8);
        }
    }
    
  3. JPA 透明加密(支持模糊查询的折中方案)
    采用 双列策略:

    • mobile_cipher 存储 Shiro 加密后 Base64 串,用于回显;
    • mobile_hash 存储 SHA256(明文+固定盐),用于精确匹配;
    • 模糊查询走 Elasticsearch 同步加密分词索引。

    实体层:

    @Entity
    @Table(name = "t_user")
    public class User {
        @Id
        private Long id;
    
        @Column(name = "mobile_cipher")
        private String mobileCipher;
    
        @Column(name = "mobile_hash", length = 64)
        private String mobileHash;
    
        @Transient
        private String mobilePlain; // 仅内存可见
    
        @PrePersist
        @PreUpdate
        private void encrypt() {
            if (mobilePlain != null) {
                mobileCipher = ShiroCrypto.encrypt(mobilePlain);
                mobileHash = DigestUtils.sha256Hex(mobilePlain + "固定盐");
            }
        }
    
        @PostLoad
        private void decrypt() {
            if (mobileCipher != null) {
                mobilePlain = ShiroCrypto.decrypt(mobileCipher);
            }
        }
    
        public void setMobile(String mobile) {
            this.mobilePlain = mobile;
        }
    
        public String getMobile() {
            return mobilePlain;
        }
    }
    
  4. DAO 层精确查询

    public interface UserRepository extends JpaRepository<User, Long> {
        @Query("select u from User u where u.mobileHash = :hash")
        Optional<User> findByMobile(@Param("hash") String hash);
    
        default Optional<User> findByMobile(String mobilePlain) {
            return findByMobile(DigestUtils.sha256Hex(mobilePlain + "固定盐"));
        }
    }
    
  5. 模糊查询
    数据同步到 Elasticsearch,索引模板对 mobile_cipher 字段使用 自定义 analyzer:

    • 先 Shiro 解密(Ingest Pipeline 里用 Java 插件);
    • 再 IK 分词;
    • 查询时用户输入“135”,直接走 mobile_cipher.prefix 分词字段,返回主键后再回 MySQL 取完整数据。
      该方案在 美团、京东数科 生产环境验证,可支持 亿级数据 100ms 内返回。

拓展思考

  1. 如果公司强制 不能落地 ES,可考虑 PostgreSQL pgcrypto + 部分索引:
    把手机号前 3 位明文冗余成 mobile_prefix 列,后 8 位用 Shiro 加密,查询时 where mobile_prefix = '135' and mobile_cipher = encrypt('13512345678'),既利用 B-Tree 又减少全表扫描。
  2. 国密改造:将 AesCipherService 替换为自研 Sm4GcmCipherService,继承 Shiro 的 DefaultBlockCipherService,重写 newCipherInstance() 返回 BouncyCastle 的 SM4Engine,过 密评 时可直接出具算法检测报告。
  3. 密钥托管:国内金融项目需把密钥放进 华为云 KMS / 阿里云 KMS,通过 BYOK 方式导入,Shiro 只在内存缓存 5 分钟,防止密钥泄露被通报。
  4. 性能调优:当字段长度 > 500 字节时,Shiro 的 Base64 编码会膨胀 33%,可在 @Converter 层再加 GZIP 压缩,压缩后再加密,存储体积减少 50% 以上,适合 医疗行业大字段加密 场景。