I’m building a web service that requires me to generate custom sessions and random passwords etc.
I was wondering if making a static class and using 1 static RNGCryptoServiceProvider instance for the entire website is a good idea?
1. Is it threadsafe from multiple http request instances?
2. Is it secure? If I allow someone to generate many sessions in a short amount of time, would it be possible to figure out the state of the RNG and predict the next sessions?
in my service other users know when someone signs in, and I originally created a new RNGCryptoServiceProvider when they login to generate a session, but my concern is if that is based off the current datetime, couldn’t someone theoretically only have to go through a few thousand sessions to “guess” the session of another user if they knew roughly what second they logged in?
public static class random
{
private static RandomNumberGenerator _rng;
protected static RandomNumberGenerator rng
{
get
{
if (_rng == null) _rng = new RNGCryptoServiceProvider();
return _rng;
}
}
public static byte[] Bytes(int number)
{
var value = new byte[number];
rng.GetBytes(value);
return value;
}
public static byte Byte { get { return Bytes(1)[0]; } }
public static int Int { get { return BitConverter.ToInt32(Bytes(4), 0); } }
public static long Long { get { return BitConverter.ToInt64(Bytes(8), 0); } }
}
1) If it’s cryptographically secure, which it’s supposed to be, then this sort of guessing should not be feasible.
2) On a side note, I suggest removing the JIT instantiation in the static property annd instead doing the following: