Skip to content

Instantly share code, notes, and snippets.

@VimanyuAgg
Created December 9, 2020 07:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VimanyuAgg/8f6f68a3676151a8e15e5cafb05da038 to your computer and use it in GitHub Desktop.
Save VimanyuAgg/8f6f68a3676151a8e15e5cafb05da038 to your computer and use it in GitHub Desktop.
AES GCM Encryption/Decryption nodejs
const IV_LENGTH = 12;
var crypto = require('crypto'),
password = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' //32 bytes (128 bits)
iv = crypto.randomBytes(IV_LENGTH);
var cipher = crypto.createCipheriv('aes-256-gcm',password, iv);
var encrypted = Buffer.from(iv).toString('hex');
encrypted += cipher.update("mysuperSecretText", 'utf8', 'hex');
encrypted += cipher.final('hex');
var tag = cipher.getAuthTag();
stringifiedTag = Buffer.from(tag).toString('base64');
encrypted += Buffer.from(tag).toString('hex'); // IV + encrypted_content + Tag is needed (in this order) if decrypted using Java
console.log("Decrypting....")
//This assumes that we are only passing hex encoded string (i.e. var encrypted) to decipher method.
var base64Decoded = Buffer.from(encrypted, 'hex'); // Use hex if encoding more than 64 bytes (can't use base64)
var ivDecrypted = base64Decoded.slice(0,12);
var encryptedEarlier = base64Decoded.slice(12,-16);
var tagForDecryption = base64Decoded.slice(-16);
var decipher = crypto.createDecipheriv('aes-256-gcm', Buffer.from(password, 'ascii'), ivDecrypted)
decipher.setAuthTag(tagForDecryption);
console.log("Decrypting....")
var dec = decipher.update(encryptedEarlier,'hex','utf8')
dec += decipher.final('utf8');
console.log(dec); //mysuperSecretText
console.log(" DECRYPTED ABOVE ***********")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment