-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 ?

AnGG
  • 679
  • 3
  • 9
  • Does this answer your question? [How to generate a cryptographically secure Double between 0 and 1?](https://stackoverflow.com/questions/2854438/how-to-generate-a-cryptographically-secure-double-between-0-and-1) – Sir Rufo Feb 19 '22 at 00:31
  • @SirRufo Its based on RNGCryptoServiceProvider which is obsolete – AnGG Feb 19 '22 at 00:38

1 Answers1

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
AnGG
  • 679
  • 3
  • 9
  • You can have a look at https://source.dot.net/#System.Private.CoreLib/Random.Xoshiro256StarStarImpl.cs,245 – Sir Rufo Feb 19 '22 at 00:12
  • @SirRufo this is a seed based Random and not a cryptography one – AnGG Feb 19 '22 at 00:17
  • 1
    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) – Sir Rufo Feb 19 '22 at 00:23
  • @SirRufo this is not needed even it may can be used because there is a RandomNumberGenerator.GetInt32 method – AnGG Feb 19 '22 at 00:40
  • 2
    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. – Alexei Levenkov Feb 19 '22 at 02:55
  • 1
    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](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Random.html#nextDouble()) show how it should be done: – President James K. Polk Feb 19 '22 at 14:34
  • 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. – AnGG Feb 25 '22 at 20:09