Search code examples
node.jssessionexpressexpress-session

What is a secure session secret?


I am using express-session and I need to create a session secret.
I have read that the secret is used for hashing.

How long and what characters should this secret have?

I was thinking about a random alphanumerical string like this:
IqFic484907I0T552hiMQ1UCJimRGL55
Can anyone give me advice on this?


Solution

  • The secret is used to sign the session id cookie, to prevent the cookie to be tampered with.

    In the end, the module responsible for creating the signature is cookie-signature, which uses crypto.createHmac() using the secret as the key and the SHA256 algorithm for hashing.

    I don't think there's a real upper limit to the length of the secret (other than, possibly, the maximum length of a string in Node, which I don't even think exists). I think that if it's longer than 256 bits (= 32 bytes), it will get hashed down to 32 bytes first.

    There's also no limitation to which characters you put in a secret. A string of random alnum characters, say 24 to 32 bytes long, should do just fine.