Interview frequency: …
Short answer
System.Random is a deterministic pseudorandom algorithm whose next values can be predicted; use RandomNumberGenerator from System.Security.Cryptography instead.
Explanation
Random uses a simple time-based seed (Clock Seed), allowing attackers to guess security tokens, account activation codes, and session keys after observing a few prior values. RandomNumberGenerator provides a cryptographically secure CSPRNG seeded from hardware and operating-system events, with convenient methods such as RandomNumberGenerator.GetInt32() and GetBytes().
Code example
// Generate a cryptographically secure six-digit OTP
int otp = RandomNumberGenerator.GetInt32(100000, 1000000);
// Generate an encrypted random key
byte[] salt = RandomNumberGenerator.GetBytes(32);Common mistakes
- Using new Random().Next() to create password reset tokens or security signatures.