簡體   English   中英

如何在 sdk v3 中將 aws kms 加密響應作為 base64 字符串。 獲取 Uint8Array 作為響應

[英]How to get aws kms encrypt response as base64 string in sdk v3. Getting Uint8Array as response

我正在使用@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 編碼的。 在 AWS 文檔中提到

有沒有辦法讓 base64 作為 nodeJs 中的響應。

AWS SDK v3 docs Docs中所述 - 只有 HTTP API 和 CLI 將獲得 Z95A6DAFCZ6A78ABB7C4E 數據。 其他媒體將得到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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM