Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 212
fancy Avatar asked Aug 05 '11 08:08

fancy


People also ask

How do I encrypt and decrypt JSON data in node JS?

const encrypted = key. encrypt(data, 'base64'); res. json({ status: 200, message: "Done", data: encrypted; });

What module would you use to encrypt data in node JS?

Node. js provides a built-in module called crypto that you can use to encrypt and decrypt strings, numbers, buffers, streams, and more.


1 Answers

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

like image 145
mak Avatar answered Oct 11 '22 02:10

mak