事件加密存储与密钥轮换
解读
在国内金融、政务、医疗等合规场景下,事件流(如交易日志、用户行为、IoT 采样)必须加密落盘,且要满足《个人信息保护法》《金融数据安全分级指南》对密钥生命周期的硬性要求:密钥最多 90 天必须轮换一次,旧密钥加密的存量数据仍须可解密,新事件用新密钥加密。面试官想考察的是:
- 能否在 Scala + JVM 生态里设计一套可水平扩展、零停机的加密方案;
- 能否把密钥版本与事件元数据绑定,实现透明解密;
- 能否在高吞吐(百万 QPS)下完成轮换,而不丢数据、不阻塞作业;
- 能否把合规审计(谁、何时、因何轮换)落地成代码,而不是口头“我们会上审计系统”。
知识点
- 信封加密:每个事件用一次性数据密钥(DEK)加密,DEK 再用主密钥(KEK)加密后与密文一起落盘;KEK 保存在 HSM 或 KMS(阿里云 KMS、腾讯云 KMS、国密 HSM)。
- 密钥版本向量:在事件头写入 keyId + keyVersion,解密时按版本路由到对应 KEK;版本号全局单调递增,Long 型自增即可。
- 轮换策略:
- 主动轮换:定时任务每 90 天生成新 KEK,只影响新事件;
- 被动轮换:检测到密钥泄露或合规工单触发,立即切换。
- 双钥缓冲:内存里同时缓存新旧两把 KEK,保证并发写不会 races;用 AtomicReference + StampedLock 实现无锁切换。
- 零拷贝加解密:使用 BouncyCastle 的 AES/GCM/NoPadding,结合 Netty ByteBuf 或 Flink MemorySegment,避免
Array[Byte]拷贝;GCM 附加认证标签 12 字节,直接写在事件尾。 - Scala 隐式类:把
Array[Byte]隐式转成EncryptedPayload,封装keyVersion: Short, ciphertext: Array[Byte], aad: Array[Byte],让业务代码无感知。 - 背压与一致性:在 Flink Kafka Sink 端实现 two-phase commit,加密失败的事件整批回滚,不重不丢;Kafka 消息 key 里带 keyVersion,方便下游按版本路由。
- 审计日志:用 SLF4J + Logback 的 Mapped Diagnostic Context 写入 JSON 审计 Topic,字段含
operator, ticketId, oldKeyId, newKeyId, rotationTime, legalBasis,供 ELK 后续合规报表。
答案
// 核心域模型
case class KeyRef(id: String, version: Short, arn: String)
case class EncryptedEvent(
keyRef: KeyRef,
iv: Array[Byte],
ciphertext: Array[Byte],
tag: Array[Byte]
)
// 加密服务 trait,方便单元测试 mock
trait CryptoAlg {
def encrypt(plain: Array[Byte]): EncryptedEvent
def decrypt(e: EncryptedEvent): Array[Byte]
}
// 生产实现
class EnvelopeCrypto(kms: KmsClient) extends CryptoAlg {
private val aesGcm = new GCMBlockCipher(new AESFastEngine)
private val keyCache = new ConcurrentHashMap[Short, Array[Byte]]
@volatile private var currentKey: KeyRef = fetchLatest()
// 每 90 天定时调用
def rotate(): Unit = this.synchronized {
val newKey = kms.createKey()
keyCache.put(newKey.version, kms.getKeyMaterial(newKey))
currentKey = newKey
Audit.log("KEY_ROTATE", oldKey = currentKey.id, newKey = newKey.id)
}
override def encrypt(plain: Array[Byte]): EncryptedEvent = {
val dek = new Array[Byte](32) // 256 bit
SecureRandom.getInstanceStrong.nextBytes(dek)
val iv = new Array[Byte](12)
SecureRandom.getInstanceStrong.nextBytes(iv)
val key = currentKey
val kekMaterial = keyCache.computeIfAbsent(key.version, _ => kms.getKeyMaterial(key))
val cipherKey = new SecretKeySpec(dek, "AES")
aesGcm.init(true, new AEADParameters(cipherKey, 96, iv))
val out = new Array[Byte](aesGcm.getOutputSize(plain.length))
val len = aesGcm.processBytes(plain, 0, plain.length, out, 0)
aesGcm.doFinal(out, len)
val tag = out.takeRight(12)
val cipherBody = out.dropRight(12)
// 用 KEK 加密 DEK
val wrappedDek = kms.encrypt(kekMaterial, dek)
EncryptedEvent(key, iv, wrappedDek ++ cipherBody, tag)
}
override def decrypt(e: EncryptedEvent): Array[Byte] = {
val kekMaterial = keyCache.get(e.keyRef.version)
val dek = kms.decrypt(kekMaterial, e.ciphertext.take(32)) // 假设 wrappedDek 固定 32 字节
val cipherKey = new SecretKeySpec(dek, "AES")
aesGcm.init(false, new AEADParameters(cipherKey, 96, e.iv))
val in = e.ciphertext.drop(32) ++ e.tag
val out = new Array[Byte](aesGcm.getOutputSize(in.length))
val len = aesGcm.processBytes(in, 0, in.length, out, 0)
aesGcm.doFinal(out, len)
out
}
}
// Flink 侧使用
class EncryptMapFunction(crypto: CryptoAlg) extends RichMapFunction[Event, EncryptedEvent] {
override def map(e: Event): EncryptedEvent =
crypto.compressAndEncrypt(e.toJson.getBytes(StandardCharsets.UTF_8))
}
关键点:
- 密钥版本随事件走,下游无需全局锁即可解密;
- rotate() 同步块只更新引用,加密线程无锁读
currentKey,百万级 QPS 无阻塞; - KMS 调用次数 = 密钥版本数,而非事件条数,大幅节省费用;
- 审计日志与事件流分离,避免敏感信息再次泄露。
拓展思考
- 国密合规:若客户强制 SM4/SM2,可把
BouncyCastle替换为 江南科友 JCE 提供者,同时 KMS 需支持 国密硬件加密卡;注意 SM4 的 GCM 模式标签长度为 16 字节,与 AES 不同,需在EncryptedEvent里额外标记cipherSuite字段。 - 密钥分层再分层:对于 跨省容灾,可引入 三级密钥体系——地域级 KEK → 应用级 KEK → DEK,轮换时只需解密再加密应用级 KEK,TB 级存量数据无需重写。
- 事件时间窗重加密:若监管要求旧密钥加密的数据必须在 30 天内用新密钥重加密,可启动 Flink 批作业,按 事件时间窗口 读取 Kafka Compact Topic,mapPartition 批量解密再加密,输出到新 Topic,原 Topic 开启 compaction 保留最新 key,实现在线热替换。
- 零信任轮换:结合 SPIFFE/SPIRE,把 密钥轮换与 Pod 身份绑定,当检测到 Sidecar 容器异常退出 时,立即吊销该 Pod 可访问的 KEK,并触发 Flink Savepoint + 重启,降低爆炸半径。