c# - Google KMS 在解密数据时出错
问题描述
当我尝试使用 Google KMS 解密我的数据时,我收到了这个错误。下面是我的解密代码。错误出现在有string plaintext
. 提前致谢
代码
public static string Encrypt(string plaintext)
{
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
//projects/progforthecloudt2020/locations/global/keyRings/pfckeyring001/cryptoKeys/pfckeys
CryptoKeyName kn = CryptoKeyName.FromUnparsed(new
Google.Api.Gax.UnparsedResourceName("GOOGLE RESOURCE ID REMOVED"));
string cipher = client.Encrypt(kn, ByteString.CopyFromUtf8(plaintext)).Ciphertext.ToBase64();
return cipher;
}
public static string Decrypt(string cipher)
{
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
CryptoKeyName kn = CryptoKeyName.FromUnparsed(new Google.Api.Gax.UnparsedResourceName("GOOGLE RESOURCE ID REMOVED"));
string plaintext = client.Decrypt(kn, ByteString.CopyFromUtf8(cipher)).Plaintext.ToBase64();
return plaintext;
}
错误
Grpc.Core.RpcException: 'Status(StatusCode=InvalidArgument, Detail="Decryption failed: the ciphertext is invalid.")'
解决方案
您正在对加密调用的结果进行 base64 编码,但是在解密调用中您没有对其进行 base64 解码。您不需要对数据进行 base64 编码。
public static void Encrypt(string projectId, string locationId, string keyRingId, string cryptoKeyId, string plaintextFile, string ciphertextFile)
{
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
CryptoKeyName cryptoKeyName =
new CryptoKeyName(projectId, locationId, keyRingId, cryptoKeyId);
byte[] plaintext = File.ReadAllBytes(plaintextFile);
EncryptResponse result = client.Encrypt(cryptoKeyName, ByteString.CopyFrom(plaintext));
// Output encrypted data to a file.
File.WriteAllBytes(ciphertextFile, result.Ciphertext.ToByteArray());
Console.Write($"Encrypted file created: {ciphertextFile}");
}
public static void Decrypt(string projectId, string locationId, string keyRingId, string cryptoKeyId, string ciphertextFile, string plaintextFile)
{
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
CryptoKeyName cryptoKeyName =
new CryptoKeyName(projectId, locationId, keyRingId, cryptoKeyId);
byte[] ciphertext = File.ReadAllBytes(ciphertextFile);
DecryptResponse result = client.Decrypt(cryptoKeyName, ByteString.CopyFrom(ciphertext));
// Output decrypted data to a file.
File.WriteAllBytes(plaintextFile, result.Plaintext.ToByteArray());
Console.Write($"Decrypted file created: {plaintextFile}");
}
推荐阅读
- windows-10-universal - 是否可以使用 nvidia Nsight 调试 cppwinrt directx12 应用程序?
- r - msmFit 后提取系数
- mysql - 错误 MySQL 连接访问被拒绝
- javascript - CSS 无限循环动画在 Safari11 或 iOS11 中不起作用
- sql - 将日期时间/时间戳转换为日期的问题
- r - SpatialPointDataFrame 和 Queen 邻接相邻列表
- android - 如何使所有 EditText 都不可编辑(反之亦然)?
- r - 为多条轨迹绘制颜色条和色阶
- jquery - laravel中所有页面的jQuery ajax url问题
- reactjs - I18n 内化反应英语和印地语