I am currently writing a simple password generator (C#). For that I need some random numbers.
Is it OK to simply use the Random class that ships with .NET or are there any known problems with that?
I am currently writing a simple password generator (C#). For that I need some random numbers.
Is it OK to simply use the Random class that ships with .NET or are there any known problems with that?
There is nothing wrong with it -- it's good enough to generate simple passwords. A simple example (source):
Random RandomClass = new Random();
int RandomNumber = RandomClass.Next(); // Random number between 1 and 2147483647
double RandomNumber = RandomClass.Next(1,10); // Random number between 1 and 10
double RandomDouble = RandomClass.NextDouble(); // Random double between 0.0 and 1.0
The article How To: Generate a Random Password (C#/VB.NET) has a very comprehensive example of generating good, easy-to-read passwords with specified complexity. It may be overkill for you, but it might provide a nice source to copy ideas from.
If you need something more for cryptography, there's another namespace for that:
System.Security.Cryptography
Specifically, you can use this:
System.Security.Cryptography.RNGCryptoServiceProvider.GetBytes(yourByte)
An example is Using Crypto for your Random Numbers in VB.NET, and another one is Crypto Random Numbers.
If you're thinking about rolling your own, the site Developer Guidance Share has some information to talk you out of it.
System.Random is not as "cryptographically strong" source of randomness. The output of the Random function is entirely predictable assuming the attacker knows (or can guess) the "seed" value that was used to create the System.Random. If you simply call new System.Random() that initial value is simply a representation of the current system time (something that an attacker can often guess very easily).
Even if the initial time is not exactly known, an attacker can check all of the potential values in a given time range by brute force.
The random generators in the System.Security.Cryptography namespace are designed for use in this kind of situation and gain their unpredictability from a number of much more secure sources.
If you're after some details on how to make System.Random
work for you this CodeBetter article is well worth reading. He gives a good overview of what the Random function is doing and how to make it 'more random' using a hashed GUID as the seed. If you just need to generate random initial passwords for user accounts (I'm assuming here) then this should be more than sufficient, the cryptography tools would probably be overkill in this case.
There is an RFC for everything! - Randomness Requirements for Security (RFC 4086).
You can also spend some big bucks on hardware to create a random seed. I think a Geiger counter is the standard for professional solutions. Most poker sites uses this nowadays.