ian.blair@softstuff

My technical musings

Using Cryptographic random numbers in Windows Universal applications C#

When building Universal applications the full set of .NET libraries aren't available and one of my favourites for generating Random numbers System.Security.Cryptography isnt available anymore. Fortunately this has been replaced with the Windows.Security.Cryptography library and although the functions don't correspond with the old library there is an easy way to generate random numbers.

using Windows.Security.Cryptography;

public Unit32 RandomNumber(UInt32 min, UInt32 max)
{
return min+(CryptographicBuffer.GenerateRandomNumber() % (max min))
// find the range of numbers needed (max min) example: 10 - 30 = 20
// then mod the random number with the range example: rnd % 20 
// then add it to the minimum value example: 10 + modded rnd
}

 

This function seems to give a pretty even spread of random numbers and is called by:

UInt32 rnd=RandomNumber(1,59);

The example above will generate one of the UK Lotto numbers.