0

Below is the implementation in ASP.NET for creating session ids (I've paraphrased).

edit (the RNG is shared):

static _randgen = new RNGCryptoServiceProvider(); 

string GetSessionId()
{
    var buffer = new byte [15];

    //fill the buffer with random bytes
    randgen.GetBytes(buffer);

    //turn the bytes into a string of letters and numbers (no unsafe chars)
    string encoding = Encode(buffer);
    return encoding; 
}

The documentation on RNGCryptoServiceProvider.GetBytes says it is thread safe, however it's not clear what kind of thread safety that means. Does it simply guarantee no deadlocks or does it guarantee two threads will get different values? Is it possible for there to be a race condition where 2 requests would pull the same session id?

Community
  • 1
  • 1
dan
  • 9,712
  • 6
  • 49
  • 62

2 Answers2

1

Since a new RNGCryptoServiceProvider object is created inside the GetSessionId function, it is not access by multiple threads.

Edit: It means it wont crash if two or more threads uses its functions. It does not guarantee any uniqueness (one thread or more) but will generate cryptographically strong random bytes.

Magnus
  • 45,362
  • 8
  • 80
  • 118
1

While GetBytes is thread safe (no deadlocks, no shared results), using it will NOT mean that the result is different each time.

Each time you call GetBytes, it is a whole new random result. Meaning that to be random it could also be a duplicate.

Granted with 15 bytes, that's a touch on the unlikely side, but it can happen.

Rangoric
  • 2,739
  • 1
  • 18
  • 18
  • Is there any documentation saying there are no shared results when calling the method from different threads? MSDN only says that the method is thread safe, which is incredibly vague. – dan Apr 19 '12 at 05:51
  • If it had shared results, it wouldn't be thread safe. Also the method ITSELF is marked as thread safe, not just the type. http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.getbytes(v=vs.100).aspx – Rangoric Apr 19 '12 at 14:01