3

I have a lambda function in node6 which has 5 env variables all encrypted with aws kms. I have the following method which takes a encrypted key and returns a decrypted key.

function decryptKMS(encryptedKey) {
console.log('inside decryptkms');
 const kms = new AWS.KMS();
    kms.decrypt({ CiphertextBlob: new Buffer(encryptedKey, 'base64') }, (err, data) => {
        if (err) {
            console.log('Decrypt error:', err);
            return callback(err);
        }
        var result = data.Plaintext.toString('ascii');
        return result;
});
}

And in my handler I'm doing this to get my decrypted keys.

decryptedkey1 = decryptKMS(encryptedkey1);
decryptedkey2 = decryptKMS(encryptedkey2);
decryptedkey3 = decryptKMS(encryptedkey3);
decryptedkey4 = decryptKMS(encryptedkey4);
decryptedkey5 = decryptKMS(encryptedkey5);

But, since node is async, the function moved to the next step before decrypting the keys. Is there anyway I can use node promises for all the keys combined, or is there any way to decrypt multiple keys at once from kms?

NPCRNPCR
  • 335
  • 3
  • 14

1 Answers1

7

Promisify your decryptKMS and combine with Promise.all

function decryptKMS(key) {
  return new Promise((resolve, reject) => {
    const kms = new AWS.KMS()

    kms.decrypt({}, (err, data) => {
      if(err) {
        reject(err)
      }
      else {
        resolve(data.Plaintext.toString('ascii'))
      }
    }) 
  })
}

const keys = [encryptedkey1, encryptedkey2, encryptedkey3]

Promise.all(keys.map(decryptKMS))
  .then(([decryptedkey1, decryptedkey2, decryptedkey3]) => {
    // use decryptedkeyN here 
  })
  .catch(console.log)
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • Note that promisifying this is unnecessary, because AWS offers a [`.promise()` method](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html#promise-property) on the AWSRequest object which does this inherently. So the code here could be simplified a bit by that. Just need `return kms.decrypt(/*params*/).promise().then(data => data.Plaintext.toString('ascii'));` – temporary_user_name Nov 20 '18 at 10:32
  • I had same issue but when i used @temporary_user_name your method, i got Promise { } when i print the decrypted keys. Please help in this – Anju Nov 10 '20 at 17:36