jeudi 23 février 2017

How to generate a cryptographically secure random integer within a range?

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 ?




Aucun commentaire:

Enregistrer un commentaire