Created
August 2, 2017 01:56
-
-
Save WendySanarwanto/8da85f9196c7e45df99eaee8c8d789cd to your computer and use it in GitHub Desktop.
Encrypt Decrypt String using AWS KMS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as aws from "aws-sdk"; | |
const kms = new aws.KMS({ region: "us-east-1" }); | |
async function doStuff() { | |
// Encrypt | |
const encrypted = await kms.encrypt({ | |
KeyId: "alias/test-key", | |
Plaintext: "abcd", | |
}).promise(); | |
console.log(Buffer.isBuffer(encrypted.CiphertextBlob)); | |
console.log(encrypted); | |
if (Buffer.isBuffer(encrypted.CiphertextBlob)) { | |
const encryptedString = Buffer.from(encrypted.CiphertextBlob).toString("base64"); | |
console.log(encryptedString); | |
// store to DynamoDB | |
// retrieve from DynamoDB | |
// Decrypt | |
const result = await kms.decrypt({ | |
CiphertextBlob: Buffer.from(encryptedString, "base64"), | |
}).promise(); | |
console.log(result); | |
if (Buffer.isBuffer(result.Plaintext)) { | |
const decrypted = Buffer.from(result.Plaintext).toString(); | |
console.log(decrypted); | |
} else { | |
throw new Error("NOT BUFFER 2"); | |
} | |
} else { | |
throw new Error("NOT BUFFER"); | |
} | |
} | |
doStuff().then(() => { | |
console.log("complete"); | |
}).catch((err) => { | |
console.error("error", err); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment