lundi 13 juillet 2020

Cryptographically secure random integer between two values

I have been using the RNGCryptoServiceProvider to create a random integer. This will generate a random integer between the lower and upper bounds of an integer.

private static RNGCryptoServiceProvider rngCryptoServiceProvider = new RNGCryptoServiceProvider();

public int Execute(int lowerBound, int upperBound)
{
    // initialize an array of bytes equal to the number of bytes in an integer
    var numberOfBytes = sizeof(int);
    var bytes = new byte[numberOfBytes];

    // fill the array with random bytes
    rngCryptoServiceProvider.GetBytes(bytes);

    // convert the byte array to an integer
    var bitsAsInteger = BitConverter.ToInt32(bytes, 0);
    
    return bitsAsInteger;
}

Now I want to generate a random integer between two integers. From what I have read, this is not a trivial task. So, I thought I might be able to randomly seed the System.Random class and use the Next() functionality to do the math. Is this a sensible approach?

private static RNGCryptoServiceProvider rngCryptoServiceProvider = new RNGCryptoServiceProvider();

public int Execute(int lowerBound, int upperBound)
{
    // initialize an array of bytes equal to the number of bytes in an integer
    var numberOfBytes = sizeof(int);
    var bytes = new byte[numberOfBytes];

    // fill the array with random bytes
    rngCryptoServiceProvider.GetBytes(bytes);

    // convert the byte array to an integer
    var bitsAsInteger = BitConverter.ToInt32(bytes, 0);

    // use the random integer to seed the non cryptographically secure Random class
    var random = new System.Random(bitsAsInteger);
    
    // use the Next() functionality to do the math to get a random number between two values
    var randomInteger = random.Next(lowerBound, upperBound);
    
    return randomInteger;
}

Is there another way to achieve the same result without having to use System.Random?




Aucun commentaire:

Enregistrer un commentaire