Skip to content

Instantly share code, notes, and snippets.

@skhatri
Last active November 13, 2015 23:55
Show Gist options
  • Save skhatri/69346096a00102918321 to your computer and use it in GitHub Desktop.
Save skhatri/69346096a00102918321 to your computer and use it in GitHub Desktop.
Encrypt Decrypt in Node using crypto
var SecurityUtil = (function(key) {
var crypto = require('crypto');
var secret=new Buffer(key);
var encrypt = function(text) {
var cipher = crypto.createCipher('aes-256-cbc', secret);
cipher.update(text, 'utf8', 'hex');
var cipherText = cipher.final('hex');
return cipherText;
};
var decrypt = function(encryptedText) {
try {
var decipher = crypto.createDecipher('aes-256-cbc', secret);
decipher.update(encryptedText, 'hex', 'utf8');
return decipher.final('utf8');
} catch (e) {
return undefined;
}
};
return {
encrypt: encrypt,
decrypt: decrypt
};
});
var util = SecurityUtil('some stuff to encrypt');
var encrypted = util.encrypt('test this out')
console.log(encrypted);
var original = util.decrypt(encrypted);
console.log(original);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment