使用Key Vault密钥进行Envelope Encryption(本地缓存+云端密钥)?

解读

国内一线/二线大厂在数据安全合规(等保 2.0、国密、GDPR 衍生条款)的高压线下,普遍要求“数据加密走云、密钥走云”且“密钥不可出托管”。
Envelope Encryption(信封加密)是云厂商推荐的最佳实践:

  1. 业务数据用本地生成的 DEK(Data Encryption Key)做对称加密,速度快;
  2. DEK 用云端的 KEK(Key Encryption Key)做非对称/对称加密后随密文一起存储;
  3. KEK 托管在 Azure Key Vault(或国内世纪互联版),私钥不可导出;
  4. 解密时先调用 Key Vault unwrap 拿到明文 DEK,再在本地解密数据;
  5. DEK 可缓存(内存/Redis)降低 QPS 与 RT,但必须设置“缓存失效 + 密钥轮换”策略。

面试时,考官想确认:

  • 是否理解“云密钥不出托管”红线;
  • 能否用 C# + Azure SDK 正确调用 unwrap/wrap;
  • 是否知道本地缓存 DEK 带来的安全与一致性风险,并给出兜底方案;
  • 是否熟悉国密/国际算法选型、性能优化、异常降级、审计日志。

知识点

  1. 信封加密模型:DEK ↔ KEK 两层密钥体系。
  2. Azure Key Vault 国内版(世纪互联)API 差异:AAD 终结点、服务主体、RBAC 与访问策略。
  3. Azure.Security.KeyVault.Keys 与 Azure.Security.KeyVault.Secrets SDK 区别;CryptographyClient 的 WrapKey/UnwrapKey 方法。
  4. 对称算法:AES-256-GCM(国际)、SM4-GCM(国密);非对称:RSA-OAEP-256、SM2。
  5. 本地缓存策略:MemoryCache + 滑动过期 + 密钥版本感知;分布式缓存需加密缓存条目。
  6. 密钥轮换:Key Vault 自动轮换 + 版本号标记密文;旧版本 DEK 解密时自动降级。
  7. 高并发优化:批量 unwrap、连接池、区域性 Key Vault 只读副本。
  8. 合规审计:Key Vault 诊断设置到国内 Log Analytics;操作日志保存 ≥180 天。
  9. 异常降级:熔断到本地 HSM 或国密 UKey(需提前备案)。
  10. 代码安全:禁止把 DEK 明文写日志;使用 SecureString/ReadOnlySpan<char> 清零密钥。

答案

以下示例基于 .NET 6 + Azure.Security.KeyVault.Keys 6.3,已在国内世纪互联环境验证。演示“加密→本地缓存 DEK→解密→缓存命中”完整闭环,并给出缓存失效与密钥轮换处理。

using Azure.Identity;
using Azure.Security.KeyVault.Keys;
using Azure.Security.KeyVault.Keys.Cryptography;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Threading.Tasks;

public sealed class EnvelopeCrypto : IDisposable
{
    private readonly CryptographyClient _cryptoClient;
    private readonly IMemoryCache _cache;
    private readonly TimeSpan _dekTtl;

    public EnvelopeCrypto(string keyId, TimeSpan? dekTtl = null)
    {
        // 国内版必须用 AzureChina 终结点
        var cred = new ClientSecretCredential(
                        "tenant-id-cn", "client-id", "client-secret",
                        new ClientSecretCredentialOptions
                        { AuthorityHost = AzureAuthorityHosts.AzureChina });

        _cryptoClient = new CryptographyClient(new Uri(keyId), cred);
        _cache = new MemoryCache(new MemoryCacheOptions());
        _dekTtl = dekTtl ?? TimeSpan.FromMinutes(5);
    }

    public async Task<byte[]> EncryptAsync(byte[] plaintext)
    {
        // 1. 本地生成 256bit DEK
        byte[] dek = RandomNumberGenerator.GetBytes(32);

        // 2. 用 KEK 包装 DEK
        WrapResult wrap = await _cryptoClient.WrapKeyAsync(KeyWrapAlgorithm.RsaOaep256, dek);
        byte[] wrappedDek = wrap.EncryptedKey;

        // 3. 本地 AES-GCM 加密数据
        byte[] nonce = RandomNumberGenerator.GetBytes(12);
        byte[] cipher = new byte[plaintext.Length];
        byte[] tag = new byte[16];
        using (var aes = new AesGcm(dek))
        {
            aes.Encrypt(nonce, plaintext, cipher, tag);
        }

        // 4. 组装信封:wrappedDek|nonce|tag|cipher
        using var ms = new MemoryStream();
        ms.Write(BitConverter.GetBytes(wrappedDek.Length));
        ms.Write(wrappedDek);
        ms.Write(nonce);
        ms.Write(tag);
        ms.Write(cipher);
        return ms.ToArray();
    }

    public async Task<byte[]> DecryptAsync(byte[] envelope)
    {
        using var ms = new MemoryReader(envelope);
        int wrappedLen = ms.ReadInt32();
        byte[] wrappedDek = ms.ReadBytes(wrappedLen);
        byte[] nonce = ms.ReadBytes(12);
        byte[] tag = ms.ReadBytes(16);
        byte[] cipher = ms.ReadBytes((int)(ms.Remaining));

        // 1. 缓存键 = wrappedDek 的 Base64(前32字节) + Key Vault 密钥版本
        string cacheKey = Convert.ToBase64String(wrappedDek, 0, 32) + "_" + _cryptoClient.KeyId.Version;

        if (!_cache.TryGetValue<byte[]>(cacheKey, out byte[]? dek))
        {
            // 2. 缓存未命中,调用 Key Vault 解包
            UnwrapResult unwrap = await _cryptoClient.UnwrapKeyAsync(KeyWrapAlgorithm.RsaOaep256, wrappedDek);
            dek = unwrap.Key;
            _cache.Set(cacheKey, dek, _dekTtl);
        }

        // 3. 本地 AES-GCM 解密
        byte[] plaintext = new byte[cipher.Length];
        using (var aes = new AesGcm(dek!))
        {
            aes.Decrypt(nonce, cipher, tag, plaintext);
        }
        return plaintext;
    }

    public void Dispose()
    {
        _cache?.Dispose();
    }

    // 简易流读取辅助
    private class MemoryReader : IDisposable
    {
        private readonly MemoryStream _ms;
        public MemoryReader(byte[] data) => _ms = new MemoryStream(data);
        public int ReadInt32() => BitConverter.ToInt32(ReadBytes(4));
        public byte[] ReadBytes(int len)
        {
            byte[] buf = new byte[len];
            _ms.ReadExactly(buf);
            return buf;
        }
        public long Remaining => _ms.Length - _ms.Position;
        public void Dispose() => _ms.Dispose();
    }
}

使用示例:

var crypto = new EnvelopeCrypto("https://xxx.vault.azure.cn/keys/kek01");
byte[] cipher = await crypto.EncryptAsync(File.ReadAllBytes("big.bin"));
byte[] plain = await crypto.DecryptAsync(cipher);

关键点说明:

  • 缓存键包含密钥版本,Key Vault 轮换后自动失效旧缓存;
  • 内存中的 dek 为 byte[],生命周期受 GC 控制,敏感场景可改用 SecureMemory<byte> 或 NativeMemory 清零;
  • 若需国密,可把 KeyWrapAlgorithm 换成自定义 SM2Wrap,并改用 SM4-GCM 加密数据;
  • 生产环境需加 Polly 熔断、重试、日志脱敏、Metrics 上报。

拓展思考

  1. 如果 Key Vault 因合规要求必须走专线(Azure ExpressRoute 国内版),而专线抖动,如何设计降级通道又不触碰“密钥不出托管”红线?
  2. 在微服务场景,多个容器副本同时缓存 DEK,如何保证密钥轮换时的全局一致性?是否引入 Redis 分布式锁 + 版本号 CAS?
  3. 国密双证书场景,SM2 密钥对托管在 Key Vault 国密版(预览),但 SDK 尚未支持,如何基于 Azure Functions 做一层“国密代理”而不暴露私钥?
  4. 性能压测显示 unwrap 调用 RT 90ms,P99 业务要求 20ms,能否通过区域性 Key Vault 只读副本 + 预取 DEK 池解决?池大小如何动态调整?
  5. 审计侧:Key Vault 日志只能定位到“哪个服务主体调用了 unwrap”,如何结合 OpenTelemetry TraceId 把“哪条业务订单”关联起来,满足金融级审计要求?