Skip to content

Instantly share code, notes, and snippets.

@CoolHandDev
Forked from AndiDittrich/AesUtil.js
Created December 29, 2018 01:44
Show Gist options
  • Select an option

  • Save CoolHandDev/9fd22b9f05c1b569a0ff292286109976 to your computer and use it in GitHub Desktop.

Select an option

Save CoolHandDev/9fd22b9f05c1b569a0ff292286109976 to your computer and use it in GitHub Desktop.
Node.js - AES Encryption/Decryption with AES-256-GCM using random Initialization Vector + Salt
/**
* AES Encryption/Decryption with AES-256-GCM using random Initialization Vector + Salt
* @type {exports}
*/
// load the build-in crypto functions
var crypto = require('crypto');
// encrypt/decrypt functions
module.exports = {
encrypt: function (text, masterkey){
try {
// random initialization vector
var iv = crypto.randomBytes(12);
// random salt
var salt = crypto.randomBytes(64);
// derive key: 32 byte key length - in assumption the masterkey is a cryptographic and NOT a password there is no need for
// a large number of iterations. It may can replaced by HKDF
var key = crypto.pbkdf2Sync(masterkey, salt, 2145, 32, 'sha512');
// AES 256 GCM Mode
var cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
// encrypt the given text
var encrypted = cipher.update(text, 'utf8', 'hex') + cipher.final('hex');
// extract the auth tag
var tag = cipher.getAuthTag();
// generate output
return salt.toString('hex') + ':' + iv.toString('hex') + ':' + tag.toString('hex') + ':' + encrypted;
}catch(e){
}
// error
return null;
},
decrypt: function (data, masterkey){
try {
// split input data data
var parts = data.split(':');
if (parts.length != 4){
return null;
}
// convert data to buffers
var salt = new Buffer(parts[0], 'hex');
var iv = new Buffer(parts[1], 'hex');
var tag = new Buffer(parts[2], 'hex');
var text = parts[3];
// derive key using; 32 byte key length
var key = crypto.pbkdf2Sync(masterkey, salt , 2145, 32, 'sha512');
// AES 256 GCM Mode
var decipher = crypto.createDecipheriv('aes-256-gcm', key, iv, 'hex');
decipher.setAuthTag(tag, 'hex');
// encrypt the given text
var decrypted = decipher.update(text, 'hex', 'utf8') + decipher.final('utf8');
return decrypted;
}catch(e){
}
// error
return null;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment