我正在尝试使用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);
答案 0 :(得分:5)
您已经对加密结果进行了base64编码,但是在尝试对其进行解密之前,尚未对它进行base64解码。
在线
ByteString ciphertext = ByteString.CopyFrom(Encoding.ASCII.GetBytes(cipher));
它应该看起来像
ByteString ciphertext = ByteString.FromBase64(cipher);
(还请注意,ByteString class具有内置的方法可用于进出Base64或从Base64进出)。