使用 Bouncy Castle 实现 `SM4TypeHandler` 并注册到配置。
解读
国内金融、政务、运营商项目普遍要求国密算法落地,MyBatis 作为数据访问层事实标准,必须能把SM4 加密字段透明地“加进去、读出来”。
面试官出这道题,想一次性验证四点:
- 是否熟悉 MyBatis 类型转换 SPI(
BaseTypeHandler体系); - 能否正确集成 Bouncy Castle 的 SM4 引擎(密钥、填充、模式、IV、字符集);
- 是否理解国密合规细节(ECB 禁用、CBC/PKCS7、128 bit 密钥、Base64 传输);
- 能否把自定义 TypeHandler 注册到 Configuration,并保证Spring Boot 打包可热插拔。
回答时只要漏掉“密钥从哪里取”“怎么防止 ECB”“注册顺序”任意一点,都会被追问到挂。
知识点
- MyBatis TypeHandler 生命周期:
setParameter→jdbc写库;getResult→ 对象属性赋值;优先级高于JdbcType默认转换。 - Bouncy Castle SM4 引擎:
SM4Engine只提供分组加密,必须外包BufferedBlockCipher+PKCS7Padding;国密要求CBC 模式,IV 16 字节随机,每次加密重新生成。 - 密钥管理:禁止把 key 硬编码,须走JCEKS 密钥库或 Spring Cloud Config 加密通道;演示时可约定
sm4.key=0123456789ABCDEFFEDCBA9876543210从环境变量注入。 - Base64 传输:数据库字段类型
varchar(256),存Base64.encodeToString(cipherBytes);读时先Base64.decode,再解密。 - 注册方式:
mybatis-config.xml里<typeHandler handler="xxx.SM4TypeHandler"/>;- Spring Boot 场景用
mybatis.type-handlers-package=com.xxx.typehandler自动扫描; - 针对特定列单独指定
@MappedTypes/@MappedJdbcTypes防止全局污染。
- 性能与安全折中:二级缓存里存的是密文,避免明文扩散;分页插件、逻辑删除插件对密文字段无法走索引,需冗余哈希列或前置分片键。
答案
public class SM4TypeHandler extends BaseTypeHandler<String> {
private static final String ALGORITHM = "SM4/CBC/PKCS7Padding";
private static final String PROVIDER = "BC";
private static final int IV_LEN = 16;
private final CipherKeyAccessor keyAccessor;
public SM4TypeHandler() {
// 优先从 Spring 环境取,否则退化成系统变量
String hexKey = Optional.ofNullable(System.getProperty("sm4.key"))
.orElseThrow(() -> new IllegalStateException("sm4.key 未配置"));
this.keyAccessor = new CipherKeyAccessor(Hex.decode(hexKey));
Security.addProvider(new BouncyCastleProvider());
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i,
String parameter, JdbcType jdbcType) throws SQLException {
try {
byte[] iv = SecureRandom.getInstanceStrong().generateSeed(IV_LEN);
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new SM4Engine()), new PKCS7Padding());
cipher.init(true, new ParametersWithIV(new KeyParameter(keyAccessor.getKey()), iv));
byte[] plain = parameter.getBytes(StandardCharsets.UTF_8);
byte[] cipherText = new byte[cipher.getOutputSize(plain.length)];
int len = cipher.processBytes(plain, 0, plain.length, cipherText, 0);
cipher.doFinal(cipherText, len);
// IV + cipherText 一起存
byte[] ivAndCipher = Bytes.concat(iv, cipherText);
ps.setString(i, Base64.getEncoder().encodeToString(ivAndCipher));
} catch (Exception e) {
throw new SQLException("SM4 加密失败", e);
}
}
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
return decrypt(rs.getString(columnName));
}
@Override
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return decrypt(rs.getString(columnIndex));
}
@Override
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return decrypt(cs.getString(columnIndex));
}
private String decrypt(String value) {
if (value == null) return null;
try {
byte[] ivAndCipher = Base64.getDecoder().decode(value);
byte[] iv = Arrays.copyOfRange(ivAndCipher, 0, IV_LEN);
byte[] cipherText = Arrays.copyOfRange(ivAndCipher, IV_LEN, ivAndCipher.length);
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new SM4Engine()), new PKCS7Padding());
cipher.init(false, new ParametersWithIV(new KeyParameter(keyAccessor.getKey()), iv));
byte[] plain = new byte[cipher.getOutputSize(cipherText.length)];
int len = cipher.processBytes(cipherText, 0, cipherText.length, plain, 0);
len += cipher.doFinal(plain, len);
return new String(plain, 0, len, StandardCharsets.UTF_8);
} catch (Exception e) {
throw new RuntimeException("SM4 解密失败", e);
}
}
}
注册到 Spring Boot:
mybatis:
type-handlers-package: com.xxx.typehandler
或在 JavaConfig 中显式:
@Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer customizer() {
return configuration -> {
configuration.getTypeHandlerRegistry()
.register(String.class, JdbcType.VARCHAR, new SM4TypeHandler());
};
}
}
拓展思考
- 密钥轮换:生产环境每 90 天换 key,老数据仍用旧 key 解密,新数据用新 key,需在行内加
key_version字段,TypeHandler 根据版本路由密钥。 - 索引失效:模糊查询无法走 B+Tree,可引入前 32 位模糊哈希列(
sm4_hash_prefix),查询时先比哈希再解密精排。 - 批量加解密:MyBatis 批处理时每次 new Cipher 性能差,可借助 ThreadLocal 缓存
BufferedBlockCipher实例,但需注意 IV 不能复用。 - 合规审计:国密验收要求“加密模块必须通过商用密码产品认证”,Bouncy Castle 本身未认证,正式交付需替换为江南科友、三未信安等过检 SDK,TypeHandler 接口不变,仅换实现类即可。