Generate a Secure Random Number

Problem

You want to generate a random number that can’t be reverse-engineered (or predicted) by a malicious user.

Solution

Use the RNGCryptoServiceProvider class in the System.Security.Cryptography namespace instead of the System.Random class.

Discussion

Computers are designed to be deterministic. As a result, they aren’t often a good source of random numbers. The numbers you generate with the System.Random class are statistically random, which means that they follow a random distribution and are suitable for modeling, simulations, computer games, and so on. However, these generators aren’t suitable for cryptographic purposes. With knowledge of the algorithm, a malicious user can look at the random numbers you generate, ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.