Skip to content

Instantly share code, notes, and snippets.

@aloncarmel
Last active January 1, 2016 07:29
Show Gist options
  • Save aloncarmel/8111927 to your computer and use it in GitHub Desktop.
Save aloncarmel/8111927 to your computer and use it in GitHub Desktop.
Encrypt and Decrypt text on nodejs with callbacks.
//Encrypt data, call callback when done for make sure everything is done.
function EncryptText(text,key,callback) {
console.log('Encrypting text');
var cipher = crypto.createCipher('aes-256-cbc',key)
var crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex');
callback(crypted);
}
//Decrypt data, call callback when done for make sure everything is done.
function DecryptText(text,key,callback) {
console.log('Decrypting text');
var decipher = crypto.createDecipher('aes-256-cbc',key)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
callback(dec);
}
//Calling the encrypt with callback because it may hang before finishing resulting in bad encryption.
EncryptText(text,key,function(crypted){
console.log(crypted);
});
//Calling the Decrypt with callback because it may hang before finishing resulting in bad encryption.
DecryptText(text,key,function(dec){
console.log(dec);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment