Search code examples
node.jscryptographycryptojs

AES256 password and iv, the right way


I want to create and manage user sessions with AES256 encrypted tokens.

I am using node's crypto library and followed this stackoverflow question.

I am using this to create session token that will be sent to frontend and stored in the backend for verification purpose and the data is stringified JSON.

Here I see two things one is password and other is iv.

so two questions,

  1. Is the iv is safe to sent to frontend (iv + "." + encData)?

  2. How should the password be generated? How about a SHA256 of (e.g. user's password that I store in db at signup)

This way I will be using a different password for each user. Is this approach correct?

P.S. Both of the answers below helped a lot, If you are here, do read all the comments and attached So question and the linked articles.


Solution

  • Let's keep to the question at hand:

    1. Is the iv is safe to sent to frontend (iv + "." + encData)?

    Well, yes. The IV may be public knowledge; as long as it is unique and - in the case of CBC mode encryption - random then this is fine. Of course, the IV and encData should be suitably encoded, for instance using hex (as in the linked answer) or base 64. This is not often done as the IV is always 16 bytes for AES, so it is easy to simply prefix the binary IV to the encData instead.

    Beware of hackers changing the input; if the dot or colon is removed then you may have just an array of one element and accessing the ciphertext may result in an error or the decryption of empty data.

    1. How should the password be generated? How about a SHA256 of (e.g. user's password that I store in db at signup)

    No, you should use a password hash for that; SHA-256 is a cryptographically secure hash but not a password hash such as PBKDF2, bcrypt, scrypt or Argon2. And if you want to store something in the DB, then please do not let that be the AES secret key generated from the password.


    This does not in any way invalidate any of the concerns in the answer of TheGreatContini. This is not security advice, just the cryptography related advice you asked for.