Skip to content

Instantly share code, notes, and snippets.

@raytung
Created October 13, 2016 09:41
Show Gist options
  • Save raytung/69fb3cf9c60bc3db730240da56e394bb to your computer and use it in GitHub Desktop.
Save raytung/69fb3cf9c60bc3db730240da56e394bb to your computer and use it in GitHub Desktop.
AWS KMS NodeJS
/*
* AWS Sdk KMS spike: (assuming node v6.6+)
* 1 - Create master key at KMS
* 2 - Copy alias or ARN
* 3 - run this i.e.
* $ node spike.js KEY_ALIAS YOUR_PLAINTEXT_TO_ENCRYPT
*/
const AWS = require('aws-sdk');
// aws-sdk is not reading my region info so i'll have to set it here
// maybe you have it working properly
AWS.config.update({ region:'ap-southeast-2' });
const kms = new AWS.KMS();
// your input args
const KeyId = process.argv[2];
const Plaintext = process.argv[3];
// http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/KMS.html#encrypt-property
const params = {
KeyId: keyId, // your key alias or full ARN key
Plaintext: secret, // your super secret. instanceof Buffer or String
};
kms.encrypt(params).promise().then(data => {
const base64EncryptedString = data.CiphertextBlob.toString('base64');
console.log('base64 encrypted string: ' + base64EncryptedString);
return base64EncryptedString;
})
.then(base64EncryptedString => {
return kms.decrypt({
CiphertextBlob: Buffer(base64EncryptedString, 'base64')
}).promise();
})
.then(data => {
console.log('Your super secret is: ' + data.Plaintext.toString('ascii'));
// do something with it
})
.catch(err => console.log(err, err.stack));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment