【问题标题】:How to get aws kms encrypt response as base64 string in sdk v3. Getting Uint8Array as response如何在 sdk v3 中将 aws kms 加密响应作为 base64 字符串。获取 Uint8Array 作为响应
【发布时间】:2021-08-19 13:08:51
【问题描述】:

我正在使用@aws-sdk/client-kms 来加密数据。我得到了 base64 字符串作为响应。现在我收到Uint8Array

 const encryptedBlob = await kms.encrypt({
    KeyId: kmsKey,
    Plaintext: Buffer.from(JSON.stringify('data to encrypt')),
  });

加密的明文。当您使用 HTTP API 或 AWS CLI 时,该值是 Base64 编码的。否则,它不是 Base64 编码的。 Mentioned in AWS docs

有什么方法可以在 nodeJs 中获取 base64 作为响应。

【问题讨论】:

    标签: amazon-web-services aws-sdk-js amazon-kms aws-sdk-js-v3


    【解决方案1】:

    AWS SDK v3 docs Docs 中所述 - 只有 HTTP API 和 CLI 才能获取 base64 数据。其他媒体将收到Uint8Array 作为响应。

    所以,我们需要一些额外的数据转换来使用SDK实现加密和解密。

    const { KMSClient, EncryptCommand, DecryptCommand } = require('@aws-sdk/client-kms');
    
    const client = new KMSClient({ region: AWS_REGION });
    
    // Encrypt
    // Convert Uint8Array data to base64
    
    const input = {
      KeyId: kmsKey,
      Plaintext: Buffer.from(JSON.stringify(credentials)),
    };
    
    const command = new EncryptCommand(input);
    const encryptedBlob = await client.send(command);
    
    const buff = Buffer.from(encryptedBlob.CiphertextBlob);
    const encryptedBase64data = buff.toString('base64');
    
    // Decrypt
    // Convert Base64 data to Uint8Array
    // Uint8Array(response) convert to string.
    
    const command = new DecryptCommand({
        CiphertextBlob: Uint8Array.from(atob(item.credentials), (v) => v.charCodeAt(0)),
      });
    const decryptedBinaryData = await client.send(command);
    
    const decryptedData = String.fromCharCode.apply(null, new Uint16Array(decryptedBinaryData.Plaintext));
    

    【讨论】:

      猜你喜欢
      • 2011-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      相关资源
      最近更新 更多