DEV Community

Discussion on: Encrypt and Decrypt Data in Node.js using aes-256-cbc

Collapse
 
noz profile image
Rich • Edited

This is a very sensitive topic to address. You have presented the article well but I'm afraid there is a problem with your example that defeats the point of the IV. If you read the definition of IV in your actual post:

NOTE: iv stands for initialization vector. The initialization vector is a random value that is used to encrypt the first block of plaintext. The initialization vector is required to decrypt the ciphertext, so it must be transmitted or stored alongside the ciphertext.

What this description may fail to impress is that an IV should be unique enough never to be used more than once with a single key. Your example essentially uses a static IV each and every time. This is bad practice and I don't recommend advising anyone to do this going forward.

What you should do is ensure the IV is suitably random (crypto-random) for each and every call and then store that IV as part of the generated cipher-text. It is perfectly OK for this to be done as you do not have to protect the IV from the cipher-text. This IV can then be used as part of the decryption process in subsequent calls.

There are more things you can do to harden up use of your key too. I recommend reviewing this very useful Gist as of writing: Node.js - AES Encryption/Decryption with AES-256-GCM using random Initialization Vector + Salt

Thanks for the article, but it would be good to update accordingly, at least around the use of the IV.

Collapse
 
jobizil profile image
Ugbem Job

Thank you so much for pointing this out and shedding more light on IV, I'll make an adjustment and proceed with this practice henceforth.