Encrypt and decrypt content with Nodejs

Written by Christoph Hartmann

Nodejs offers great support for cryptography. Under the hood it uses openssl and ships with a Javascript api. Unfortunately the api is not always as intuitive as it should be, especially when you have to deal with error codes. To make you life easier, I collected various approaches for encryption with AES 256.

Update: All examples are available on Github node-crypto-examples, too.

Encryption mode

The first decision is the AES encryption mode. Currently I recommend the CTR mode. You may want to read Evaluation of Some Blockcipher Modes of Operation or On the Security of CTR + CBC-MAC. The next nodejs version comes with support for GCM to do authenticated encryption. Until then you have to use approaches like Encrypt-then-MAC and combine the encryption with the generation of SHA hashs.

Examples

Encrypt and decrypt text

Encrypt and decrypt buffers

Encrypt and decrypt streams

Use GCM for authenticated encryption

If you replace aes-256-ctr with aes-256-gcm you may think everything works as expected. Unfortunately this will result with a confusing error message: TypeError: error:00000000:lib(0):func(0):reason(0).

Authenticated encryption includes a hash of the encrypted content and helps you to identify manipulated encrypted content.

You need to set the authentication tag via decrypt.setAuthTag(), which is currently only available if you use crypto.createCipheriv(algorithm, key, iv) with an initialization vector. GCM’s security is dependent on choosing a unique initialization vector for each encryption.

The new GCM mode is available in nodejs 0.11. Try it with n via

npm install -g n
sudo n 0.11.13
n use 0.11.13 crypto-gcm.js

Also take a look at the nodejs tests for more tests with different setups.

Conclusion

I hope the samples help you to get started with nodejs encryption.

If you have any questions contact me via Twitter @chri_hartmann or Github

See also: