Lets say I want to cookie for a user, would simply going to /dev/urandom, generating a 1024 bit string, checking if it already exists (and looping till I get a unique one) suffice? Or should I be generating the key based on something else, because this is prone to a exploit somehow?
The short answer is yes. The long answer is also yes.
The man page for
For the purpose of producing a "cookie": such a cookie should be such that no two users share the same cookie, and that it is computationally infeasible for anybody to "guess" the value of an existing cookie. A sequence of random bytes does that well, provided that it uses randomness of adequate quality (
There are some tricks which are doable if you want shorter cookies and still wish to avoid looking up for collisions in your database. But this should hardly be necessary for a cookie (I assume a Web-based context). Also, remember to keep your cookies confidential (i.e. use HTTPS, and set the cookie "secure" flag).
Yes, it's a great way.
@Thomas's explanation nails it. And he is completely right to criticize the
But skip "checking if it already exists". That check is pointless. It ain't gonna happen. (The chances of that happening are lower than the probability of being struck by lightning -- multiple times -- in the same day.)