C#中使用Google KMS API的加密值长度与postman中API直接生成的密文长度不同

Encrypted value length using Google KMS API in C# is different from the length of encrypted text generated directly from the API in postman

我正在尝试使用 google KeyManagementService 在 C# 中加密文本。 我无法使用 KeyManagementServiceClient.Decrypt 方法解密 KeyManagementServiceClient.Encrypt 生成的密码。解密给我:

Grpc.Core.RpcException: Status(StatusCode=InvalidArgument, Detail="Decryption failed: the ciphertext is invalid.")

我尝试使用 google 试试这个 API link 来获取密码以及由 google API 和C# 结果不同。

例如: 诉苦文字:text

来自 C# 的密码:

TaRQSJ2KXrdmJJT6MmlD8RrcxzPJEa1jwAXWJ1puXg6nbl80aBcSLQBqSYOONfXhpZx8SyxCdB6mqTgr8uLJoAjva+Q4kN/p0+9RL2Sp2mHq4wjmZQ==

来自API的密码:

TaRQSJ2KXv9ntnS7IszL077KNPtGJnqF9pSNiWANsq8gD0whezUSKwBqSYOOKKMifiWrfPDnHL5xETHPPlms0ztjkqa5hjdtkHwpzByLzi68A40

有人解决过这个问题吗?

这是我的示例代码

 KeyManagementServiceClient keyManagementServiceClient =KeyManagementServiceClient.Create(channel);
  byte[] plaintext=Encoding.ASCII.GetBytes("test");
  EncryptRequest request = new EncryptRequest
   {
       CryptoKeyPathName = new CryptoKeyPathName("test-project", "global", "test-key", "encryption-key"),
        Plaintext = ByteString.CopyFrom(plaintext),
   };
   EncryptResponse response =keyManagementServiceClient.Encrypt(request);
   var cipher = 
   Convert.ToBase64String(response.Ciphertext.ToByteArray());

 //Decrypt
  ByteString ciphertext = ByteString.CopyFrom(Encoding.ASCII.GetBytes(cipher));

  DecryptRequest req = new DecryptRequest
        {
            CryptoKeyName = new CryptoKeyName("test-project", "global", "test-key", "encryption-key"),
            Ciphertext = ciphertext,
        };
        // Make the request
        DecryptResponse res = keyManagementServiceClient.Decrypt(req);

您已经对加密结果进行了 base64 编码,但在尝试解密之前还没有对其进行 base64 解码。

在行

ByteString ciphertext = ByteString.CopyFrom(Encoding.ASCII.GetBytes(cipher));

它应该看起来像

ByteString ciphertext = ByteString.FromBase64(cipher);

(另请注意,ByteString class 具有用于转 to/from Base64 的内置方法,如果这是您想要做的。)