微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 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));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。