unable to use @google-cloud/kms nodejs module to decrypt secret

756 Views Asked by At

Code:

contents = encryptedWebhookSecret[0].toString();
console.log(typeof contents);
console.log(contents);
const formattedName = kmsClient.cryptoKeyPath(PROJECT, 'global', KEYRING, KEY);
const kmsDecryptRequest = { 
    name: formattedName,
    ciphertext: contents //encryptedWebhookSecret
};  
console.log("Decrypting webhook secret...");
return kmsClient.decrypt(kmsDecryptRequest);

encryptedWebhookSecret is the result of a download() operation using @google-cloud/storage client. this returns a [Buffer], which I cast to a string. I log the encrypted string, it's value is correct. I can download the encrypted secret using gsutil from the command line and gcloud kms decrypt works fine.

This error seems like it is saying the string is not encoded properly (should it not be utf8?).

The values for PROJECT, KEYRING, and KEY have been double and triple checked and are correct.

Error:

ERROR: Error: invalid encoding at Error (native) at Object.decode (/user_code/node_modules/@google-cloud/kms/node_modules/@protobufjs/base64/index.js:105:19) at Type.DecryptRequest$fromObject [as fromObject] (eval at Codegen (/user_code/node_modules/@google-cloud/kms/node_modules/@protobufjs/codegen/index.js:50:33), <anonymous>:12:15) at Type.fromObject (/user_code/node_modules/@google-cloud/kms/node_modules/protobufjs/src/type.js:538:25) at serialize (/user_code/node_modules/@google-cloud/kms/node_modules/grpc/src/protobuf_js_6_common.js:70:23) at Object.final_requester.sendMessage (/user_code/node_modules/@google-cloud/kms/node_modules/grpc/src/client_interceptors.js:802:37) at InterceptingCall._callNext (/user_code/node_modules/@google-cloud/kms/node_modules/grpc/src/client_interceptors.js:418:43) at InterceptingCall.sendMessage (/user_code/node_modules/@google-cloud/kms/node_modules/grpc/src/client_interceptors.js:460:8) at InterceptingCall._callNext (/user_code/node_modules/@google-cloud/kms/node_modules/grpc/src/client_interceptors.js:424:12) at InterceptingCall.sendMessage (/user_code/node_modules/@google-cloud/kms/node_modules/grpc/src/client_interceptors.js:460:8)

EDIT: When I try using a base64 encoding, I get "TypeError: Key must be a buffer at TypeError (native) at new Hmac (crypto.js:93:16) at Object.Hmac (crypto.js:91:12) at isRequestValid (/user_code/index.js:81:8) at decryptWebhookSecret.then (/user_code/index.js:119:21)".

2

There are 2 best solutions below

0
On BEST ANSWER

The issue was that ciphertext needs to be base64 encoded.

1
On

The Node client library requires that plaintexts and ciphertexts be submitted as Buffers. Which is easy enough-- you'll just do ciphertext: Buffer.from(contents) in your sample above.