如何在 SDK v3 中获取 AWS kms 加密响应作为 Base64 字符串。获取 Uint8Array 作为响应

Arp*_*dav 3 amazon-web-services amazon-kms aws-sdk-js aws-sdk-js-v3

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

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

加密的明文。当您使用 HTTP API 或 AWS CLI 时,该值是 Base64 编码的。否则,它不是 Base64 编码的。AWS文档中提到

有没有办法在nodeJs中获取base64作为响应。

Arp*_*dav 7

如AWS SDK v3 文档中所述- 只有 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));
Run Code Online (Sandbox Code Playgroud)

  • 最后一行可以简化为“Buffer.from(decryptedBinaryData.Plaintext).toString()” (3认同)