【问题标题】:Nodejs async issue while decrypting aws kms keys解密aws kms密钥时出现Nodejs异步问题
【发布时间】:2017-11-21 20:41:40
【问题描述】:

我在 node6 中有一个 lambda 函数,它有 5 个 env 变量,所有变量都用 aws kms 加密。我有以下方法,它采用加密密钥并返回解密密钥。

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;
});
}

在我的处理程序中,我这样做是为了获取我的解密密钥。

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

但是,由于节点是异步的,因此该函数在解密密钥之前移至下一步。无论如何我可以对所有组合的密钥使用节点承诺,或者有什么方法可以一次从 kms 解密多个密钥?

【问题讨论】:

    标签: node.js asynchronous aws-lambda aws-kms


    【解决方案1】:

    承诺您的decryptKMS 并与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)
    

    【讨论】:

    • 请注意,没有必要对此进行承诺,因为 AWS 在 AWSRequest 对象上提供了一个 .promise() method,它本身就是这样做的。所以这里的代码可以稍微简化一下。只需要return kms.decrypt(/*params*/).promise().then(data => data.Plaintext.toString('ascii'));
    • 我遇到了同样的问题,但是当我使用 @temporary_user_name 你的方法时,当我打印解密的密钥时,我得到了 Promise { }。请帮忙
    猜你喜欢
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多