Skip to content

Instantly share code, notes, and snippets.

@mdelano
Created April 5, 2017 19:35
Show Gist options
  • Save mdelano/57f1afc2c25bd1d68aa2479e87a91e8e to your computer and use it in GitHub Desktop.
Save mdelano/57f1afc2c25bd1d68aa2479e87a91e8e to your computer and use it in GitHub Desktop.
This is an example of creating encryption keys using AWS KMS
/**
* The following is an example of creating encryption keys using AWS KMS.
*/
var Q = require('q');
var AWS = require('aws-sdk');
var kms = new AWS.KMS({region: 'us-east-1'});
/**
* Example of create a "data" key with AWS KMS. Data keys are just encryption keys
* with the added benefit of being stored in KMS' hardware encryption layer.
*/
var createCryptoKey = function() {
var deferred = Q.defer();
/**
* The Key ID is an AWS KMS identifier for the "master" key. The master key is used
* for for generating and crytping data keys
*/
kms.generateDataKey({KeyId: 'alias/MyMasterKey', NumberOfBytes: 16}, function(err, data) {
if (err) {
logger.error('Could not create encryption key', err);
deferred.reject();
} else {
/**
* The plain text key is the unecrypted key that can be used for crypto in the application
*/
logger.debug('Plantext crypto key', new Buffer(data.Plaintext).toString('hex'));
/**
* The ciphertext blob is the encrypted key that you can safely store next to the data you'd like to encrypt/decrypt
*/
logger.debug('Encrypted crypto key', new Buffer(data.CiphertextBlob).toString('hex'));
deferred.resolve(data.Plaintext);
}
});
return deferred.promise;
}
/**
* This method will decrypt the encrypted key given by KMS in response to the generateDataKey method.
* When you want o encrypt something you should first decrypt your crypto key with this method,
* @param {*} cipherText This is the encrypted encryption key (see the CiphertextBlob above)
*/
var decryptCryptoKey = function (cipherText) {
var deferred = Q.defer();
kms.decrypt({CiphertextBlob: new Buffer(cipherText, "hex")}, function (err, data) {
if (err) {
logger.error('Could not get encryption key', err);
deferred.reject();
} else {
logger.debug('Plantext crypto key', new Buffer(data.Plaintext).toString('hex'));
deferred.resolve(data.Plaintext);
}
});
return deferred.promise;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment