Skip to content

Instantly share code, notes, and snippets.

@jbubriski
Created August 23, 2013 19:29
Show Gist options
  • Save jbubriski/6323070 to your computer and use it in GitHub Desktop.
Save jbubriski/6323070 to your computer and use it in GitHub Desktop.
Cryptographic Random Number Generation example.
public class Example
{
private static int GetRandomNumber(int max)
{
var bytes = new byte[3];
var cr = new System.Security.Cryptography.RNGCryptoServiceProvider();
cr.GetBytes(bytes);
// Get 3 random digits as a string, and parse it as an int, then keep it between 0 and the max
var key = int.Parse((bytes[0] % 10) + (bytes[1] % 10).ToString() + (bytes[2] % 10)) * max / 1000;
return key;
}
private static int GetRandomNumber(int min, int max)
{
var value = GetRandomNumber(max - min);
return min + value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment