How can I generate a cryptographically secure pseudorandom number in C#?

C#Cryptography

C# Problem Overview


Is there any fast implementation of cryptographically secure pseudorandom number generator (CSPRNG) for C# 3.0 (.NET Framework 3.5), for authentication tokens?

C# Solutions


Solution 1 - C#

using System.Security.Cryptography;
...
using(RandomNumberGenerator rng = new RNGCryptoServiceProvider())
{
    byte[] tokenData = new byte[32];
    rng.GetBytes(tokenData);

    string token = Convert.ToBase64String(tokenData);
}

Solution 2 - C#

Upd 2022 in .Net 6 RNGCryptoServiceProvider() is obsolete, usage of static methods of RandomNumberGenerator is recommended

private string GetRandomlyGenerateBase64String(int count)
{
    return Convert.ToBase64String(RandomNumberGenerator.GetBytes(count));
}

Solution 3 - C#

That depends on what you mean by fast...

There is no really fast secure random generator. If you want fast, you should use the regular Random class. If you want secure you should use the random generator in the Cryptography namespace, but that is significantly slower. You simply can't have both.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlon GubkinView Question on Stackoverflow
Solution 1 - C#John GietzenView Answer on Stackoverflow
Solution 2 - C#Serg.IDView Answer on Stackoverflow
Solution 3 - C#GuffaView Answer on Stackoverflow