Skip to content

Instantly share code, notes, and snippets.

@chris-rock
Last active February 21, 2023 10:31
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save chris-rock/fe87dd35d6168512a2f7 to your computer and use it in GitHub Desktop.
Save chris-rock/fe87dd35d6168512a2f7 to your computer and use it in GitHub Desktop.
Use GCM for authenticated encryption in nodejs
// Nodejs encryption with GCM
// Does not work with nodejs v0.10.31
// Part of https://github.com/chris-rock/node-crypto-examples
var crypto = require('crypto'),
algorithm = 'aes-256-gcm',
password = '3zTvzr3p67VC61jmV54rIYu1545x4TlY',
// do not use a global iv for production,
// generate a new one for each encryption
iv = '60iP0h6vJoEa'
function encrypt(text) {
var cipher = crypto.createCipheriv(algorithm, password, iv)
var encrypted = cipher.update(text, 'utf8', 'hex')
encrypted += cipher.final('hex');
var tag = cipher.getAuthTag();
return {
content: encrypted,
tag: tag
};
}
function decrypt(encrypted) {
var decipher = crypto.createDecipheriv(algorithm, password, iv)
decipher.setAuthTag(encrypted.tag);
var dec = decipher.update(encrypted.content, 'hex', 'utf8')
dec += decipher.final('utf8');
return dec;
}
var hw = encrypt("hello world")
// outputs hello world
console.log(decrypt(hw));
@tomalex0
Copy link

@JohnAdamsy
Copy link

Yep...I am getting the same error too. Current node js -v0.10.32. For some weird reason, it run the first time then it just went crazy on the subsequent runs.

@chris-rock
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment