Skip to content

Instantly share code, notes, and snippets.

@Vitsaus
Forked from adrianbravo/encrypt-decrypt.js
Created September 28, 2012 07:58
Show Gist options
  • Save Vitsaus/3798537 to your computer and use it in GitHub Desktop.
Save Vitsaus/3798537 to your computer and use it in GitHub Desktop.
Basic Node.js crypto cipher/decipher example.
var crypto = require('crypto')
, key = 'salt_from_the_user_document'
, plaintext = 'password'
, cipher = crypto.createCipher('aes-256-cbc', key)
, decipher = crypto.createDecipher('aes-256-cbc', key);
cipher.update(plaintext, 'utf8', 'base64');
var encryptedPassword = cipher.final('base64')
decipher.update(encryptedPassword, 'base64', 'utf8');
var decryptedPassword = decipher.final('utf8');
console.log('encrypted :', encryptedPassword);
console.log('decrypted :', decryptedPassword);
@vasudev-hv
Copy link

vasudev-hv commented Feb 12, 2019

Encryption and decryption should be

    var encryptedPassword = cipher.update(plaintext, 'utf8', 'base64');
    encryptedPassword += cipher.final('base64')
    console.log('encrypted :', encryptedPassword);
  
    var decryptedPassword = decipher.update(encryptedPassword, 'base64', 'utf8');
    decryptedPassword += decipher.final('utf8');      
    console.log('decrypted :', decryptedPassword);

Dont ignore output of update()

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