微服务数据加密传输与密钥轮换最佳实践概述微服务间的通信与数据存储需同时满足传输加密与静态加密。配合自动密钥轮换与身份标识(SPIFFE),可实现零信任的数据保护。传输加密:mTLS与服务身份type MtlsConfig = { ca: string; cert: string; key: string; peerIdentity: string }
function setupMtls(config: MtlsConfig) {
// 伪代码:在HTTP客户端/服务端启用双向TLS
return {
ca: config.ca,
cert: config.cert,
key: config.key,
servername: config.peerIdentity // SPIFFE ID: spiffe://org/service
}
}
静态加密:信封加密(AES-GCM)import { randomBytes, createCipheriv, createDecipheriv } from 'crypto'
type CipherText = { iv: string; tag: string; data: string }
function encryptEnvelope(plain: Buffer, dataKey: Buffer): CipherText {
const iv = randomBytes(12)
const cipher = createCipheriv('aes-256-gcm', dataKey, iv)
const enc = Buffer.concat([cipher.update(plain), cipher.final()])
const tag = cipher.getAuthTag()
return { iv: iv.toString('base64url'), tag: tag.toString('base64url'), data: enc.toString('base64url') }
}
function decryptEnvelope(ct: CipherText, dataKey: Buffer): Buffer {
const iv = Buffer.from(ct.iv, 'base64url')
const tag = Buffer.from(ct.tag, 'base64url')
const data = Buffer.from(ct.data, 'base64url')
const decipher = createDecipheriv('aes-256-gcm', dataKey, iv)
decipher.setAuthTag(tag)
return Buffer.concat([decipher.update(data), decipher.final()])
}
自动密钥轮换class KeyRotator {
currentKey: Buffer
nextKey: Buffer | null = null
rotateAt: number
constructor(ttlMs: number) {
this.currentKey = randomBytes(32)
this.rotateAt = Date.now() + ttlMs
}
needRotate(): boolean { return Date.now() > this.rotateAt }
scheduleNext(ttlMs: number) { this.nextKey = randomBytes(32); this.rotateAt = Date.now() + ttlMs }
commitRotation() { if (this.nextKey) { this.currentKey = this.nextKey; this.nextKey = null } }
}
服务网格与策略使用服务网格(如Istio/Linkerd)强制mTLS与策略下发基于SPIFFE ID进行服务身份与授权运维要点传输层启用mTLS并审计证书与SPIFFE身份数据层采用AES-GCM信封加密并定期轮换数据密钥在网格中统一管理策略与密钥生命周期,保留审计日志以上方案可在微服务环境中实现可验证的端到端数据保护与密钥治理。

发表评论 取消回复