I have to generate a uniform, secure random integer within a given range for a program that generates passwords. Right now I use this :
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] rand = new byte[4];
rng.GetBytes(rand);
int i = BitConverter.ToUInt16(rand, 0);
int result = i%max; //max is the range's upper bound (the lower is 0)
Is this method safe to use for cryptographic purposes ? If not, how should I do it ?
You can have a look to CryptoRandom class taken from https://gist.github.com/1017834 which is the Original version by Stephen Toub and Shawn Farkas. In this class they implement several random generators that seem to be cryptographically secures.
I have used the following version in my projects for random int generation.