Skip to content

Instantly share code, notes, and snippets.

@wohugb
Forked from csanz/encrypt_decrypt.js
Last active August 29, 2015 13:57
Show Gist options
  • Save wohugb/9612658 to your computer and use it in GitHub Desktop.
Save wohugb/9612658 to your computer and use it in GitHub Desktop.
function encrypt(text,key){
var cipher = crypto.createCipher('aes-256-cbc',key)
var crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex');
return crypted;
}
function decrypt(text,key){
var decipher = crypto.createDecipher('aes-256-cbc',key)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}
var hw = encrypt("hello world",'d6F3Efeq')
decrypt(hw,'d6F3Efeq')
// feel free to change >> d6F3Efeq
// To test just copy + paste the above inside the node shell
// TIP: always encrypt IDs before sending via HTTP
# 引用 http://stackoverflow.com/questions/6953286/node-js-encrypting-data-that-needs-to-be-decrypted
var crypto = require('crypto');
var assert = require('assert');
var algorithm = 'aes256'; // or any other algorithm supported by OpenSSL
var key = 'password';
var text = 'I love kittens';
var cipher = crypto.createCipher(algorithm, key);
var encrypted = cipher.update(text, 'utf8', 'hex') + cipher.final('hex');
var decipher = crypto.createDecipher(algorithm, key);
var decrypted = decipher.update(encrypted, 'hex', 'utf8') + decipher.final('utf8');
assert.equal(decrypted, text);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment