Google KMS выдает ошибку при расшифровке данных - PullRequest
0 голосов
/ 15 апреля 2020

Когда я пытаюсь расшифровать свои данные с помощью 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.")'

1 Ответ

2 голосов
/ 15 апреля 2020

Вы 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}");
}
...