jedisct1 / libsodium

A modern, portable, easy to use crypto library.
https://libsodium.org
Other
12.15k stars 1.73k forks source link

Is Generic Hashing safe for generating Session cookie ids? #1031

Closed SomeAB closed 3 years ago

SomeAB commented 3 years ago

As recommended in the documentation, I'm using pwhash for passwords, but now I need to generate cookies with unique session ids. So my question is, whether generic hashing (which uses blake) is safe for this purpose?

In order to keep the sessionid unique, I want to concatenate Username (guaranteed to be unique) with random data, and hash it.

How much length should be ideal, if I'm using (which I assume is the right one) the "Single-part example with a key".

Label: Question

jedisct1 commented 3 years ago

Hi Ahmad,

In order to get unique identifiers, hashing is not required at all. Just create a 128-bit random value with randombytes_buf() and you'll get a unique identifier.

This is slightly off-topic, but usernames are generally not unique. If a user's account is deleted and another one is recreated with the same name, you may not want to carry over valid sessions from the previous user.

Using session identifiers assume that the set of valid sessions if stored server-side. This is the safest way to handle sessions, and they can easily be removed when a user disconnects, or after a change of privileges.

If you want stateless sessions, then a hash function can come in handy. But instead of session identifiers, you may want to hash something like { user_id (not name!), expiration_timestamp }, the latter limiting the validity period of the token. But sessions cannot be prematurely ended, which may or may not be an issue for your application.

For that purpose, generichash with a secret key works perfectly, although you could also use crypto_auth().