I have an encrypted file stored in a Google Cloud Storage bucket that was generated with the following command line:
gcloud kms encrypt --location=global --keyring=my-keyring --key=-my-key --plaintext-file=my-file --ciphertext-file=my-file.enc
I am now trying to decrypt such file in a Cloud Run service with the following code:
const kms = require('@google-cloud/kms');
const client = new kms.KeyManagementServiceClient();
const file = storage.bucket("my-bucket").file('my-file.enc');
const name = client.cryptoKeyPath( 'projectId', 'global', 'my-keyring', 'my-key' );
let encrypted = (await file.download())[0];
const [result] = await client.decrypt({name, encrypted });
I am getting the following error:
Error: Decryption failed: verify that 'name' refers to the correct CryptoKey.
Which, according to this, is misleading and should be considered as not being properly deciphered. I cannot shake the feeling that I am missing a base64 encode/decode somewhere but I don't seem to find the solution.
If I run the decryption from the command-line it works just fine.
Any help is very appreciated.
Thanks.
EDIT: Problem solved thanks to this awesome community. Here goes the steps to make this work, in case others face the same issue:
Encrypt the file using the following command line and upload it via the web UI.
gcloud kms encrypt --location=global --keyring=my-keyring --key=-my-key --plaintext-file=my-file --ciphertext-file=my-file.enc
Decrypt using the following code:
const kms = require('@google-cloud/kms');
const client = new kms.KeyManagementServiceClient();
const file = storage.bucket("my-bucket").file('my-file.enc');
const name = client.cryptoKeyPath( 'projectId', 'global', 'my-keyring', 'my-key' );
let encrypted = (await file.download())[0];
const ciphertext = encrypted .toString('base64');
const [result] = await client.decrypt({name, ciphertext});
console.log(Buffer.from(result.plaintext, 'base64').toString('utf8'))