Angular使用AWS KMS加密文本后在.NET API中解密无法获取正确明文的问题求助
解决Angular AWS KMS加密后.NET Web API解密乱码的问题
看起来你遇到的核心问题是跨语言传输KMS密文时的字节编码处理不一致,导致解密后的明文变成乱码。虽然单独在Angular或.NET端加密解密正常,但跨端传输时没处理好CiphertextBlob的格式转换,让我们一步步解决这个问题:
问题根源
Angular中AWS KMS返回的CiphertextBlob是Uint8Array类型(二进制字节数组),如果直接把这个数组通过HTTP传输,或者错误地转换成字符串,会导致后端接收到的字节流损坏;而.NET端如果直接用损坏的字节数组解密,自然会得到乱码。
解决方案步骤
1. 修正Angular端:将密文转为Base64字符串传输
HTTP传输二进制数据最可靠的方式是用Base64编码,所以我们需要把Uint8Array转成Base64字符串再发给后端:
// 先写一个工具函数,把Uint8Array转成Base64 function uint8ArrayToBase64(arr: Uint8Array): string { return btoa(String.fromCharCode(...arr)); } // 加密并处理密文 const client = new KMSClient({ region: environment.region, credentials: { accessKeyId: '<accessKeyId>', secretAccessKey: '<secretAccessKey>', }, }); try { const command = new EncryptCommand({ KeyId: '<kmsKeyId>', Plaintext: this.form.value['mobileNumber'], EncryptionContext: environment.context, }); const response = await client.send(command); // 把CiphertextBlob转成Base64字符串 const base64Ciphertext = uint8ArrayToBase64(response.CiphertextBlob as Uint8Array); console.log(base64Ciphertext); // 发送这个base64字符串给.NET后端 } catch (err) { console.error('加密失败:', err); }
2. 修正.NET端:解码Base64字符串再解密
后端接收到Base64字符串后,先把它转回字节数组,再传入KMS的解密请求:
var client = new AmazonKeyManagementServiceClient("<accessId>", "<secret>", Amazon.RegionEndpoint.USEast1); var encryptionContext = new Dictionary<string, string>() { {"data", "mobile-number" }, {"purpose","test encryption" }, {"origin","us-east-1" } }; // 假设从请求中拿到的Base64密文是ciphertextBase64 string ciphertextBase64 = "从Angular端接收的Base64字符串"; byte[] ciphertextBytes = Convert.FromBase64String(ciphertextBase64); var decryptRequest = new DecryptRequest() { CiphertextBlob = new MemoryStream(ciphertextBytes), EncryptionContext = encryptionContext, // 注意:解密时KeyId不是必须的,KMS会自动识别密文对应的密钥,除非你有特殊需求可以保留 // KeyId = "alias/<keyname>" }; var decryptData = await client.DecryptAsync(decryptRequest); var plainText = Encoding.UTF8.GetString(decryptData.Plaintext.ToArray());
额外检查点
为了确保万无一失,还要确认以下几点:
- EncryptionContext完全一致:Angular端的
environment.context必须和.NET端的字典完全匹配,包括键名、值的大小写和拼写——KMS对EncryptionContext的匹配是严格区分大小写的,不匹配会导致解密失败或结果异常。 - 密钥区域一致:Angular加密用的KMS密钥所在区域,必须和.NET端KMS客户端的区域(
Amazon.RegionEndpoint.USEast1)一致,否则无法解密。 - 编码统一:Angular中传入的字符串会被AWS SDK自动转成UTF-8字节,所以.NET端解密后必须用
Encoding.UTF8来转换明文,不要用ASCII或其他编码。
这样处理后,跨端的加密解密应该就能正常得到正确的明文了。
内容的提问来源于stack exchange,提问作者Arkadeep
相关产品推荐
相关产品推荐

