如何在 sdk v3 中获取 aws kms 加密响应作为 base64 字符串获取 Uint8Array 作为响应

问题描述

我使用 @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 作为响应。

解决方法

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