Recipe 7.4 · C#
Secure Random Tokens
Problem
Password-reset links, e-mail confirmation codes, API keys and one-time download links need values
nobody can guess. Legacy code uses new Random(), Guid.NewGuid() or a timestamp, and stores
the token in plain text, so anyone who can read the table can reset any password.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not this: predictable values, stored as-is.
var random = new Random();
string code = random.Next(100000, 999999).ToString();
string resetToken = Guid.NewGuid().ToString("N");
db.Execute("UPDATE dbo.AppUser SET ResetToken = @t WHERE Id = @id",
new { t = resetToken, id = userId });
The improved recipe
Generate tokens with RandomNumberGenerator, encode them URL-safely, store only a SHA-256 hash
with an expiry, and compare hashes in constant time.
using System;
using System.Security.Cryptography;
using System.Text;
namespace ImproveCode.Security;
public static class SecureTokens
{
private const string Digits = "0123456789";
/// <summary>URL-safe token with byteLength bytes of entropy
/// (32 bytes = 256 bits = 43 characters).</summary>
public static string Create(int byteLength = 32)
{
ArgumentOutOfRangeException.ThrowIfLessThan(byteLength, 16);
byte[] bytes = RandomNumberGenerator.GetBytes(byteLength);
return ToBase64Url(bytes);
}
/// <summary>Numeric code for SMS or e-mail. Short-lived and
/// rate-limited use only.</summary>
public static string NumericCode(int digits = 6)
{
ArgumentOutOfRangeException.ThrowIfLessThan(digits, 6);
ArgumentOutOfRangeException.ThrowIfGreaterThan(digits, 10);
return RandomNumberGenerator.GetString(Digits, digits);
}
/// <summary>Hash to store in the database instead of the
/// token itself.</summary>
public static string HashForStorage(string token)
{
ArgumentException.ThrowIfNullOrEmpty(token);
byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(token));
return Convert.ToHexString(hash);
}
public static bool Matches(string token, string storedHash)
{
if (string.IsNullOrEmpty(token) || storedHash.Length != 64)
{
return false;
}
byte[] actual = SHA256.HashData(Encoding.UTF8.GetBytes(token));
byte[] expected;
try
{
expected = Convert.FromHexString(storedHash);
}
catch (FormatException)
{
return false;
}
return CryptographicOperations.FixedTimeEquals(actual, expected);
}
private static string ToBase64Url(byte[] bytes) =>
Convert.ToBase64String(bytes)
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_');
}
Usage for a password reset, as a sketch:
string token = SecureTokens.Create();
await resets.SaveAsync(new PasswordReset(
UserId: user.Id,
TokenHash: SecureTokens.HashForStorage(token),
ExpiresUtc: time.GetUtcNow().AddMinutes(30)));
string link = $"https://app.example.com/reset?token={token}";
How it works
RandomNumberGenerator draws from the operating system's cryptographic generator. Random is a
fast pseudo-random generator meant for simulations; its output can be predicted from a few
samples, and older .NET versions seeded it from the clock, so two servers starting together could
produce the same sequence. A GUID is unique but not designed to be unpredictable, and version 4
GUIDs carry only 122 random bits in a recognizable format.
Thirty-two random bytes give 256 bits of entropy, far beyond any brute-force attempt. Base64url
encoding swaps + and / for - and _ and drops padding, so the token can go into a URL or a
file name without escaping.
RandomNumberGenerator.GetString (new in .NET 8) picks each character uniformly from the
choices. The common shortcut GetInt32() % 1000000 is close, but home-made modulo arithmetic is
where bias creeps in, and the built-in method removes the question.
Storing SHA256(token) instead of the token means a leaked table or a curious administrator
can't use the outstanding reset links. A plain SHA-256 is enough here, unlike passwords, because
the token has 256 bits of entropy; nobody can guess inputs to try. When the user clicks the link,
you hash what they bring, look up the row by hash, check the expiry, and delete the row so it
works only once.
Variations and pitfalls
- Six-digit codes have only a million possibilities. They're acceptable only with a short expiry (minutes), a small number of attempts, and rate limiting per account and per IP.
- For API keys, add a readable prefix such as
ick_live_before the random part. It makes leaked keys easy to spot in logs and by secret scanners, and it costs nothing. - On .NET 9 and later,
System.Buffers.Text.Base64Url.EncodeToStringreplaces the hand-writtenToBase64Url. The manual version keeps the recipe working on .NET 8. - Put reset tokens in the URL path or a query string only over HTTPS, and set
Referrer-Policy: no-referreron the reset page so the token doesn't leak to third-party scripts through theRefererheader. - For session-style tokens your own app issues and reads back, ASP.NET Core's Data Protection
ITimeLimitedDataProtectorcan carry the user ID and expiry inside the token itself.