Sunday, July 04, 2010

Huge cryptographically secure random numbers

Just a tiny implementation example on how to use .NET crypto-package to create really huge pseudo random numbers.
Add approprite controls and rock.
(in my example I just kicked out the number on a webpage - feel free to do it where ever you like)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Numerics;
using System.Security.Cryptography;

namespace numbers
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

private static BigInteger GetRandom()
{
RandomNumberGenerator ran = RNGCryptoServiceProvider.Create();
byte[] ranbytes = new Byte[256];
//ex: Byte[20] gives 8 bit * 20 = 160 bit ~ 50 digits
//ex: Byte[2] gives 8 bit * 2 = 16 bit = +- 32768
//ex: Byte[128] gives 8 bit * 128 = 1024 bit ~ 300 digits

//fill the byte array with cryptographically strong random bytes
ran.GetBytes(ranbytes);

//put the random bytes into a bigInteger
BigInteger mynum = new BigInteger(ranbytes);
return mynum;
}

protected void Button1_Click(object sender, EventArgs e)
{

//Roll the really really big dice :)
BigInteger roll = GetRandom();
result.Text= roll.ToString();

}
}
}

No comments: