How to encrypt data that needs to be decrypted in node.js?

fancy picture fancy · Aug 5, 2011 · Viewed 42.4k times · Source

We are using bcrypt for hashing passwords and data that never needs to be decrypted. What should we do to protect other user information that does need to be decrypted?

For example, let's say that we didn't want a user's real name to be in plain text in case someone was to obtain access to the database. This is somewhat sensitive data but also needs to be called from time to time and displayed in plain text. Is there a simple way to do this?

Answer

mak picture mak · Aug 5, 2011

You can use the crypto module:

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);

Edit

Now createCipher and createDecipher is deprecated instead use createCipheriv and createDecipheriv