Skip to main content

How to Create Random Bytes with RandomNumberGenerator.GetBytes in C#

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

RandomNumberGenerator.GetBytes(8) returns eight cryptographically strong random bytes in one call, the kind Microsoft's documentation recommends for something like a random password. Every call gives new bytes, so the ones you get won't match this post's.

Microsoft's reference: Creates an array of bytes with a cryptographically strong random sequence of values. It's a static method of the RandomNumberGenerator class, whose remarks say: Using the static members of this class is the preferred way to generate random values.

Syntax​

Syntax
using System.Security.Cryptography;

byte[] <bytes> = RandomNumberGenerator.GetBytes(<count>);
PartWhat it is
RandomNumberGeneratorThe class in System.Security.Cryptography that makes cryptographically strong random values
GetBytes(<count>)A static method: there's no object to create or dispose
<count>How many bytes. The reference: The number of bytes of random values to create.
<bytes>A new byte[] of that length. The reference: An array populated with cryptographically strong random values.

The Example​

A console app called RandomBytes makes two arrays of eight random bytes and prints them as numbers, then makes a short gift card code from four more.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n RandomBytes
cd RandomBytes
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/RandomBytes/RandomBytes.csproj:
Determining projects to restore...
Restored /Users/you/source/RandomBytes/RandomBytes.csproj (in 42 ms).
Restore succeeded.

dotnet new console -n RandomBytes creates a folder named RandomBytes with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or RandomBytes.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the using and eight bytes:

Program.cs (eight bytes)
using System.Security.Cryptography;

// Eight random bytes: each one is a number from 0 to 255.
byte[] first = RandomNumberGenerator.GetBytes(8);
Console.WriteLine($"First call: {string.Join(" ", first)}");

using System.Security.Cryptography; lets the code use RandomNumberGenerator without its full name. GetBytes(8) returns a new array of eight bytes, and string.Join prints them with a space between them.

Then a second call:

Program.cs (a second call)
// A second call gives eight new bytes.
byte[] second = RandomNumberGenerator.GetBytes(8);
Console.WriteLine($"Second call: {string.Join(" ", second)}");

The second call makes a second array, with its own bytes.

Last, a code:

Program.cs (a code)
// Four random bytes as text, for a short code such as a gift card number.
string code = Convert.ToHexString(RandomNumberGenerator.GetBytes(4));
Console.WriteLine($"Gift card code: {code}");

Convert.ToHexString turns each byte into two characters, 0 to 9 and A to F, so four bytes make an eight-character code.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
First call: 46 55 70 25 206 40 56 13
Second call: 14 45 82 135 38 74 180 31
Gift card code: 4BE8CE09

macOS-style terminal window titled Terminal — RandomBytes showing dotnet run printing First call: 46 55 70 25 206 40 56 13, Second call: 14 45 82 135 38 74 180 31 and Gift card code: 4BE8CE09

These are the bytes of the recorded run. Yours will be different, because every call makes new ones:

  • The two calls gave two different sets of eight numbers, each from 0 to 255.
  • The four code bytes became eight characters, 4BE8CE09.
  • A second run of the same program printed 8 97 166 229 194 139 117 11, 16 25 8 9 234 234 19 227 and the code 0F09BAAF.

The Complete File​

macOS-style code window titled Program.cs — RandomBytes showing using System.Security.Cryptography, two calls to RandomNumberGenerator.GetBytes with a count of 8 printed with string.Join, and a gift card code made with Convert.ToHexString from RandomNumberGenerator.GetBytes with a count of 4

Program.cs
using System.Security.Cryptography;

// Eight random bytes: each one is a number from 0 to 255.
byte[] first = RandomNumberGenerator.GetBytes(8);
Console.WriteLine($"First call: {string.Join(" ", first)}");

// A second call gives eight new bytes.
byte[] second = RandomNumberGenerator.GetBytes(8);
Console.WriteLine($"Second call: {string.Join(" ", second)}");

// Four random bytes as text, for a short code such as a gift card number.
string code = Convert.ToHexString(RandomNumberGenerator.GetBytes(4));
Console.WriteLine($"Gift card code: {code}");

Common Mistakes​

MistakeWhat happensDo this instead
Using Random for a password or a secret codeIts numbers come from an algorithm and a seed: two new Random(42) objects gave the same bytes, 62 23 186 150 174 4 205 59. The Random reference: If the same seed is used for separate Random objects, they will generate the same series of random numbers.Use RandomNumberGenerator. The same reference: To generate a cryptographically secure random number, such as one that's suitable for creating a random password, use one of the static methods in the RandomNumberGenerator class.
Printing the array with Console.WriteLine(bytes)It printed System.Byte[], the array's typePrint the bytes with string.Join(" ", bytes): 20 113 177 254
Asking for as many bytes as the code needs charactersEach byte becomes two hex characters, so GetBytes(8) made a 16-character codeAsk for half as many bytes: GetBytes(4) made 8 characters
new RandomNumberGenerator()error CS0144: Cannot create an instance of the abstract type or interface 'RandomNumberGenerator'Call the static method, RandomNumberGenerator.GetBytes(<count>)

FAQ​

How do I fill an array I already have?​

Use RandomNumberGenerator.Fill. The reference: Fills a span with cryptographically strong random bytes. An array of six zeros held 194 132 126 65 134 67 after RandomNumberGenerator.Fill(buffer).

How do I get a random number in a range instead?​

Use RandomNumberGenerator.GetInt32. The reference: Generates a random integer between a specified inclusive lower bound and a specified exclusive upper bound using a cryptographically strong random number generator. So GetInt32(1, 7) rolls a die: five rolls gave 5, 4, 5, 4 and 4.

Conclusion​

RandomNumberGenerator.GetBytes(count) returns a new array of count cryptographically strong random bytes, with no object to create. Use it instead of Random for anything secret, print the bytes with string.Join or Convert.ToHexString, and expect different bytes every time.

Additional Resources​