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