69

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

Alon Gubkin
  • 56,458
  • 54
  • 195
  • 288

3 Answers3

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

    string token = Convert.ToBase64String(tokenData);
}
John Gietzen
  • 48,783
  • 32
  • 145
  • 190
  • 35
    Cryptanalysis of the WinAPI GUID generator shows that, since the sequence of V4 GUIDs is pseudo-random, given the initial state one can predict up to the next 250 000 GUIDs returned by the function UuidCreate. This is why GUIDs should not be used in cryptography, e.g., as random keys. (from http://en.wikipedia.org/wiki/Globally_Unique_Identifier) – configurator Nov 03 '09 at 16:36
  • 1
    This isn't specifically cryptography, tho. And, it would be difficult to predict the initial state of the machine. – John Gietzen Nov 03 '09 at 17:07
  • 17
    A common attack is to DDoS a server until it is restarted. Then predicting the initial state (system clock) is much easier. – LaJmOn Feb 15 '12 at 16:01
15

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));
}
Serg.ID
  • 1,604
  • 1
  • 21
  • 25
3

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.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    If you're willing to do interop with a native crypto implementation you can have both excellent performance (several times faster than `System.Random`) and security. – CodesInChaos Nov 22 '14 at 13:59
  • 16
    @CodesInChaos: So; fast, secure, simple - pick any two. :) – Guffa Nov 22 '14 at 14:24