利用 `AES/GCM` 实现手机号在入库前加密、查询后解密,写出 `TypeHandler`。
解读
国内《个人信息保护法》把手机号列为“敏感个人信息”,明文存储直接违反法律。MyBatis 的 TypeHandler 是“字段级”加解密的天然扩展点:写入时把明文手机号加密成 byte[] 再落库;读取时把 byte[] 解密回明文。整个流程对 DAO 层零侵入,业务代码只关心 String 类型,加密细节完全下沉到 JDBC 参数与结果集处理阶段。
知识点
- AES/GCM 参数:128 bit 的 IV(Nonce)+ 128 bit 的 AuthTag,必须随机生成并随密文一起存储,否则无法解密。
- 密钥管理:国内生产环境禁止把密钥写死在代码或配置文件,必须通过 KMS(阿里云 KMS、腾讯云 KMS、华为云 KMS 或自建 Vault)获取,且支持定期轮转。
- TypeHandler 生命周期:由 MyBatis 维护单例,必须线程安全;因此
Cipher不能做成成员变量,每次加解密都重新创建。 - 字段长度估算:GCM 密文长度 = 明文长度 + 16 Byte Tag;手机号 11 位 UTF-8 占 11 Byte,Base64 后约 40 字符,数据库字段类型建议
VARCHAR(64)或VARBINARY(64)。 - 性能优化:读远多于写,可开启 MyBatis 二级缓存,但密文必须作为缓存 key 的一部分,否则会出现“同一密文不同明文”的脏读;也可在内存里再包一层本地缓存(Caffeine),缓存明文对象,降低 KMS 调用次数。
- 合规审计:每次加解密记录“数据主体 ID、操作类型、时间戳、密钥版本”到合规日志(Log4j2 Kafka Appender → 公司审计系统),保留日志 3 年以上。
答案
public final class AesGcmPhoneTypeHandler extends BaseTypeHandler<String> {
private static final String TRANSFORMATION = "AES/GCM/NoPadding";
private static final int GCM_IV_LENGTH = 12; // 96 bit
private static final int GCM_TAG_LENGTH = 128; // bit
private static final SecureRandom RANDOM = new SecureRandom();
// 从 KMS 获取当前版本的密钥,示例写死,生产必须走 KMS
private static SecretKey fetchKey() {
byte[] keyBytes = KMSClient.getCurrentKey("phone-aes-gcm");
return new SecretKeySpec(keyBytes, "AES");
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i,
String parameter, JdbcType jdbcType) throws SQLException {
try {
byte[] iv = new byte[GCM_IV_LENGTH];
RANDOM.nextBytes(iv);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
cipher.init(Cipher.ENCRYPT_MODE, fetchKey(), spec);
byte[] cipherText = cipher.doFinal(parameter.getBytes(StandardCharsets.UTF_8));
// 拼接:IV + CipherText
byte[] ivAndCipher = ByteBuffer.allocate(iv.length + cipherText.length)
.put(iv)
.put(cipherText)
.array();
// 落库存成 VARBINARY
ps.setBytes(i, ivAndCipher);
} catch (GeneralSecurityException e) {
throw new SQLException("AES/GCM encrypt error", e);
}
}
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
byte[] ivAndCipher = rs.getBytes(columnName);
return ivAndCipher == null ? null : decrypt(ivAndCipher);
}
@Override
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
byte[] ivAndCipher = rs.getBytes(columnIndex);
return ivAndCipher == null ? null : decrypt(ivAndCipher);
}
@Override
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
byte[] ivAndCipher = cs.getBytes(columnIndex);
return ivAndCipher == null ? null : decrypt(ivAndCipher);
}
private String decrypt(byte[] ivAndCipher) throws SQLException {
try {
ByteBuffer buffer = ByteBuffer.wrap(ivAndCipher);
byte[] iv = new byte[GCM_IV_LENGTH];
buffer.get(iv);
byte[] cipherText = new byte[buffer.remaining()];
buffer.get(cipherText);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
cipher.init(Cipher.DECRYPT_MODE, fetchKey(), spec);
byte[] plain = cipher.doFinal(cipherText);
return new String(plain, StandardCharsets.UTF_8);
} catch (GeneralSecurityException e) {
throw new SQLException("AES/GCM decrypt error", e);
}
}
}
注册方式(Spring Boot):
@Configuration
@MapperScan("com.xxx.dao")
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer customizer() {
return configuration -> {
configuration.getTypeHandlerRegistry()
.register(String.class, JdbcType.VARBINARY, new AesGcmPhoneTypeHandler());
};
}
}
实体字段保持 String 即可:
@TableName("t_user")
public class User {
@TableField(typeHandler = AesGcmPhoneTypeHandler.class, jdbcType = JdbcType.VARBINARY)
private String phone;
}
拓展思考
- 密钥轮换:KMS 支持“后向解密、前向加密”策略——老数据仍用旧密钥解密,新数据用新密钥加密。
TypeHandler里需在密文前再追加 1 Byte 的密钥版本号,解密时先读版本再去 KMS 拿对应密钥,实现零停机轮换。 - 性能压测:AES-NI 指令集下,单核 QPS 可达 2 万+,但 KMS 网络调用 RT 20 ms 会成为瓶颈;可引入“本地密钥缓存”+“密钥加密密钥(KEK)”二级机制:每天从 KMS 拉一次 KEK,缓存到本地内存,减少 99% 的 KMS 调用。
- 搜索方案:密文无法直接
LIKE,国内主流做法有三种:- 前后戳哈希索引:入库时额外保存
sha256(phone)前 8 位作为索引字段,查询时先算哈希再精确匹配,满足 90% 业务场景; - 可搜索加密(SSE):基于倒排索引的 AES-CTR+HMAC,需要额外 ES 集群,适合 ToC 超大规模;
- 同态加密:目前性能太低,企业级尚未落地。
- 前后戳哈希索引:入库时额外保存
- 多租户隔离:SaaS 场景下每个租户一个密钥,密钥与 tenantId 绑定,
TypeHandler里通过TenantContext动态获取密钥,防止租户间密文泄露。 - 单元测试:使用 JUnit5 + Testcontainers 启动 MySQL 容器,插入 1000 万条手机号,验证加解密正确率 100%,并压测 5 min 观察 GC 停顿不超过 200 ms,确保上线后不会触发 STW 导致接口超时。
把上述要点吃透,面试时不仅能写出健壮代码,还能把合规、性能、运维、搜索、测试全链路讲清楚,直接拉开与其他候选人的差距。