-
-
Save deepal/da4606378fb81e3819268a3ffffe489e to your computer and use it in GitHub Desktop.
Use GCM for authenticated encryption in nodejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment