How to get NextDouble from cryptogaphy random RandomNumberGenerator
Asked Answered
A

1

-1

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 ?

Anuria answered 18/2, 2022 at 23:56 Comment(2)
Does this answer your question? How to generate a cryptographically secure Double between 0 and 1?Dubitation
@SirRufo Its based on RNGCryptoServiceProvider which is obsoleteAnuria
A
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
Anuria answered 18/2, 2022 at 23:56 Comment(7)
You can have a look at source.dot.net/#System.Private.CoreLib/…Dubitation
@SirRufo this is a seed based Random and not a cryptography oneAnuria
Did you see the method NextDouble()? Did you read the comment? The methods shows you how to transform an unsigned 64bit int into a double. It does not matter who has built that unsigned 64bit int (seed based, cryptography or magic dust random)Dubitation
@SirRufo this is not needed even it may can be used because there is a RandomNumberGenerator.GetInt32 methodAnuria
This is a dangerous example of code as it misrepresents what it is doing by using Crypto random generator while in reality it gives only 32bits of randomness for 64bytes long value.Hippel
I agree this answer is incorrect because it fails to be full entropy, and almost certainly anyone using a cryptographic rng would expect a full-entropy double value from nextDouble. The javadocs for the equivalent Java method show how it should be done:Remscheid
The main point was the randomness even if the range is not full, but you are right also., I have updated my answer to return to full range random.Anuria

© 2022 - 2024 — McMap. All rights reserved.