Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
@jpletcher
Copy link

jpletcher commented Jan 12, 2013

If you password is longer than 15 (or so) characters, should be:

var encryptedPassword = cipher.update(plaintext, 'utf8', 'base64');
encryptedPassword = encryptedPassword + cipher.final('base64')

var decryptedPassword = decipher.update(encryptedPassword, 'base64', 'utf8');
decryptedPassword = decryptedPassword + decipher.final('utf8');

@kgao
Copy link

kgao commented Mar 28, 2014

copyObj.length = 165
TypeError: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length

@kgao
Copy link

kgao commented Mar 28, 2014

fix by do not specify the type when decode.

@sdeering
Copy link

sdeering commented Apr 21, 2014

See this Gist for more expansive coding of this: https://gist.github.com/sdeering/7153714

@jenrik
Copy link

jenrik commented Aug 15, 2014

Fixed it so that it works probably when encrypting a string longer than 15 characters: https://gist.github.com/jenrik/766f81a147d61b6a9557

@dkhonig
Copy link

dkhonig commented Feb 25, 2016

I would not copy this code if I were you. CBC mode requires an IV (Initialization Vector) to initialize the first block of plaintext. This example is extremely broken and insecure. Look for an example that uses an IV and make sure that IV is unique for each time you encrypt something.

@arendondiosa
Copy link

arendondiosa commented Jan 14, 2017

TypeError: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length

Note: This error appears when the Decrypt function receives other string different to the encrypted string 😄 👊
Source: It just occurred to me

@omartrigui
Copy link

omartrigui commented Feb 28, 2017

@dkhonig Agree.

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