1

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

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

我尝试使用 google Try this API 链接来获取密码,并且 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);
4

1 回答 1

5

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

在行

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

相反,它应该看起来像

ByteString ciphertext = ByteString.FromBase64(cipher);

(另请注意,ByteString 类具有进出 Base64 的内置方法,如果您要这样做的话。)

于 2019-03-29T17:23:03.523 回答