Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Numbers and Math

C# RandomNumberGenerator class

Reference for System.Security.Cryptography.RandomNumberGenerator: generate cryptographically secure random bytes, integers, strings and tokens in C#.

System.Security.Cryptography.RandomNumberGenerator produces cryptographically secure random data, drawn from the operating system's secure source. Use it whenever unpredictability matters: session tokens, password-reset links, salts, encryption keys, nonces and one-time codes. Random is faster and can be seeded, but its output can be predicted, so it must never protect anything.

All the useful members are static, so you rarely create an object. The class is thread-safe. You need using System.Security.Cryptography;.

C#
using System.Security.Cryptography;

byte[] key = RandomNumberGenerator.GetBytes(32);   // 256 random bits
int digit = RandomNumberGenerator.GetInt32(10);    // 0 to 9

Try it

C# Bytes, integers and tokens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Choosing from a character set

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public static byte[] RandomNumberGenerator.GetBytes(int count)
public static void   RandomNumberGenerator.Fill(Span<byte> data)
public static int    RandomNumberGenerator.GetInt32(int toExclusive)
public static int    RandomNumberGenerator.GetInt32(int fromInclusive, int toExclusive)
public static string RandomNumberGenerator.GetString(ReadOnlySpan<char> choices, int length)   // recent .NET
public static void   RandomNumberGenerator.Shuffle<T>(Span<T> values)                          // recent .NET
public static RandomNumberGenerator RandomNumberGenerator.Create()
Name Description
count Number of random bytes to return. Must not be negative.
data The buffer to fill with random bytes.
fromInclusive / toExclusive Bounds of the integer range. The upper bound is exclusive.
choices, length The allowed characters and how many to draw (GetString).

Returns: a new array, nothing (Fill), an integer in the range, or a string.

Errors: ArgumentOutOfRangeException for a negative count and for GetInt32(0) or a negative single bound; ArgumentException for the two-argument form when the range is empty or reversed (GetInt32(5, 5)).

Usage notes

  • Use it for secrets, not for convenience. Anything that someone could abuse by guessing it (API keys, reset tokens, CSRF values) should come from here.
  • Do not reduce bytes with %. bytes[0] % 10 favors some digits because 256 is not a multiple of 10. GetInt32(10) removes the bias.
  • Token length. Use at least 16 random bytes (128 bits) for tokens. Encode them as hex or Base64 for transport; the encoding does not add strength.
  • Passwords and salts. Use a password hashing function (Rfc2898DeriveBytes.Pbkdf2) with a fresh 16-byte salt from GetBytes. Do not hash the password with a plain hash.
  • No seeds. There is no way to repeat a sequence, which also makes it unsuitable for tests that need determinism. Hide it behind an interface and fake it in tests.
  • Cost. Each call asks the operating system for entropy. It is fast enough for tokens, but too slow for a million-iteration simulation; use Random there.
  • Obsolete pattern. Older code creates RandomNumberGenerator.Create() and calls GetBytes(byte[]) on the instance. The static methods are simpler and allocate less. If you do create an instance, dispose it.
  • Version note. GetInt32 and the static GetBytes arrived in .NET Core 3.0 and .NET 6. GetString and Shuffle are recent additions; both compile on the .NET 10 runner here.