Skip to content

Instantly share code, notes, and snippets.

@DannyWhyte
Created December 11, 2019 09:47
Show Gist options
  • Save DannyWhyte/bd074829f0717d2a5b7e5169eee24966 to your computer and use it in GitHub Desktop.
Save DannyWhyte/bd074829f0717d2a5b7e5169eee24966 to your computer and use it in GitHub Desktop.
AES-GCM-256 Encryption & Decryption Using NODE
const crypto = require('crypto');
const generateMasterKey = function (bytes) {
return crypto.randomBytes(bytes).toString('base64')
}
const encryptAes256Gcm = (text, cryptoConfigObject) => {
try {
// random initialization vector
const iv = crypto.randomBytes(16);
// random salt
const salt = crypto.randomBytes(64);
// derive encryption key
const key = crypto.pbkdf2Sync(cryptoConfigObject.masterKey, salt, cryptoConfigObject.iterations, cryptoConfigObject.keyLength, cryptoConfigObject.digest);
// AES 256 GCM Mode
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
// encrypt the given text
const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
// extract the auth tag
const tag = cipher.getAuthTag();
// generate output
return Buffer.concat([salt, iv, tag, encrypted]).toString('base64')
} catch (err) {
return err
}
}
/**
* Decrypts text by given key
* @param String base64 encoded input data
* @param Buffer masterkey
* @returns String decrypted (original) text
*/
const decryptAes256Gcm = (encdata, cryptoConfigObject) => {
try {
// base64 decoding
const bData = Buffer.from(encdata, 'base64');
// convert data to buffers
const salt = bData.slice(0, 64);
const iv = bData.slice(64, 80);
const tag = bData.slice(80, 96);
const text = bData.slice(96);
// derive key using; 32 byte key length
const key = crypto.pbkdf2Sync(cryptoConfigObject.masterKey, salt, cryptoConfigObject.iterations, cryptoConfigObject.keyLength, cryptoConfigObject.digest);
// AES 256 GCM Mode
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(tag);
return decipher.update(text, 'binary', 'utf8') + decipher.final('utf8')
}
catch (err) {
return err
}
}
// =========================== module ends here =======================
const toFetchFromDb = {
"masterKey": "sfcpnnjFG6dULJfo1BEGqczpfN0SmwZ6bgKO5FcDRfI=",
"iterations": 2333,
"keyLength": 32,
"digest": "sha512"
}
// string data which will be encrypted and then decrypted
var dataToEncrypt = 'some string to encrypt and then decrypt'
const encryptedData = encryptAes256Gcm(dataToEncrypt, toFetchFromDb)
console.log('encrypted data ->', encryptedData)
console.log('data encrypted, now decrypting it ...')
console.log('decrypted data ->', decryptAes256Gcm(encryptedData, toFetchFromDb))
// uncomment below console statememt to generate new masterkey
// console.log('your masterKey is :', generateMasterKey(32))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment