views:

66

answers:

2

Most web applications depend on some kind of session with the user (for instance, to retain login status). The session id is kept as a cookie in the user's browser and sent with every request.

To make it hard to guess the next user's session these session-ids need to be sparse and somewhat random. The also have to be unique.

The question is - how to efficiently generate session ids that are sparse and unique?

This question has a good answer for unique random numbers, but it seems not scalable for a large range of numbers, simply because the array will end up taking a lot of memory.

EDIT:

  • GUIDs are considered unsafe as far as security (and randomness) go.
  • The core problem is making sure the numbers are unique, i.e. they don't repeat and making it efficient.
A: 

You could take a look at the RNGCryptoServiceProvider if you are using .NET.

http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=775

This is a cryptographically secure way of generating random numbers.

Josh Barker
@jbarker: It's a good way to go with random number generator, but it doesn't solve the problem of not repeating them, i.e. making them unique.
Asaf R
This is true, but if strong enough, it is highly unlikely that there will be collisions. If you are worried about this or performance, have another process generate, validate the uniqueness, and store them securely. Either that or use these in combination with GUIDs.
Josh Barker
What andras said would be correct or use RNGCrypto in combination with a GUID as I had mentioned above:RRRRGGGGR = RNGCryptoG = GUID
Josh Barker
+2  A: 

If you want them to be unique and not easily guessable, why not combine these?

Take a counter (generates unique value for new session) and append random bits generated by a CSPRNG. Make sure to get the minimum number of bits required right.

This should work on a farm as well without hitches: just prefix the counter that is local to a server with an id that is unique to that server.

SSSSCCCCCRRRRRR

Where S is server id that created the session, C is the server local counter and R is a crypto random.

(Disclaimer: the number of letters do not correspond to the number of digits/bits you should use in any way. :)

Unique, secure.

andras