Dan Bright's .NET Weblog

Crypto Random Numbers

Note to self (and anyone else it will help):

 

public static int GetCryptographicRandomNumber(int lBound, int uBound)

{

RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

// Assumes lBound >= 0 && lBound < uBound

// returns an int >= lBound and < uBound

uint urndnum;

byte[] rndnum = new Byte[4];

if (lBound == uBound-1)

{

// test for degenerate case where only lBound can be returned

return lBound;

}

uint xcludeRndBase = (uint.MaxValue - (uint.MaxValue%(uint)(uBound-lBound)));

do

{

rng.GetBytes(rndnum);

urndnum = System.BitConverter.ToUInt32(rndnum,0);

}

while (urndnum >= xcludeRndBase);

return (int)(urndnum % (uBound-lBound)) + lBound;

}

 

Thanks to Kevin Stewart for this.

Comments

Andrew said:

Sweet! This came in handy for one of my programs... Thanks for the code!

# July 15, 2008 12:05 AM