Skip to content

Instantly share code, notes, and snippets.

@csanz
Created August 30, 2011 16:06
Show Gist options
  • Save csanz/1181250 to your computer and use it in GitHub Desktop.
Save csanz/1181250 to your computer and use it in GitHub Desktop.
Simple String Encryption & Decryption with Node.js
function encrypt(text){
var cipher = crypto.createCipher('aes-256-cbc','d6F3Efeq')
var crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex');
return crypted;
}
function decrypt(text){
var decipher = crypto.createDecipher('aes-256-cbc','d6F3Efeq')
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}
var hw = encrypt("hello world")
decrypt(hw)
// feel free to change >> d6F3Efeq
// To test just copy + paste the above inside the node shell
// TIP: always encrypt IDs before sending via HTTP
@hitautodestruct
Copy link

Hey

DeprecationWarning: crypto.createCipher is deprecated.

Please note that createCipher has been deprecated so use this instead.
Taken from this SO answer

const crypto = require('crypto');
const algorithm = 'aes-256-ctr';
const ENCRYPTION_KEY = 'Put_Your_Password_Here'; // or generate sample key Buffer.from('FoCKvdLslUuB4y3EZlKate7XGottHski1LmyqJHvUhs=', 'base64');
const IV_LENGTH = 16;

function encrypt(text) {
    let iv = crypto.randomBytes(IV_LENGTH);
    let cipher = crypto.createCipheriv(algorithm, Buffer.from(ENCRYPTION_KEY, 'hex'), iv);
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return iv.toString('hex') + ':' + encrypted.toString('hex');
}

function decrypt(text) {
    let textParts = text.split(':');
    let iv = Buffer.from(textParts.shift(), 'hex');
    let encryptedText = Buffer.from(textParts.join(':'), 'hex');
    let decipher = crypto.createDecipheriv(algorithm, Buffer.from(ENCRYPTION_KEY, 'hex'), iv);
    let decrypted = decipher.update(encryptedText);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    return decrypted.toString();
}

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