'How to get NextDouble from cryptogaphy random RandomNumberGenerator

I want to have a cryptographic random double, since RNGCryptoServiceProvider is obsolete in .NET 6 this question is not relevant How to generate a cryptographically secure Double between 0 and 1?

RandomNumberGenerator is recommended, so does RandomNumberGenerator have any method like Random.NextDouble that will return double equals or great than 0.0 and less than 1.0 ?



Solution 1:[1]

For .NET 6 and above

using System.Security.Cryptography;

static double NextDouble()
{
    ulong nextULong = BitConverter.ToUInt64(RandomNumberGenerator.GetBytes(sizeof(ulong)));

    return (nextULong >> 11) * (1.0 / (1ul << 53));
}

For example

double randomDobule = NextDouble();
Console.WriteLine(randomDobule);

// 0.9007393363493708

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1