Good day, I have a function to generate random keys and it works fine.
public string CreatePassword(int length)
{
string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder res = new StringBuilder();
Random rnd = new Random();
while (0 < length--)
{
res.Append(valid[rnd.Next(valid.Length)]);
}
return res.ToString();
}
However, when I call the function twice from the same function I get the same key, when they should be different.
private void button3_Click(object sender, EventArgs e)
{
string lusuario = CreatePassword(12);
string lclave = CreatePassword(12);
tbUsuario.Text = lusuario;
tbClave.Text = lclave;
}
Obtaining this result:
The class
Random
is not a true random number generator. It is a generatorpseudo-aleatorio
. Any instance ofRandom
has a certain number of states, and when calledNext(o NextDouble o NextBytes)
can return data that appears to be random.So what is the problem?
You are using a new instance of
Random
on each method call. The parameterless constructor forRandom
takes the current date and time as the seed, and a fair amount of code can usually be executed before the internal timer determines that the current date and time has changed. Therefore, we are using the same seed repeatedly and getting the same results every time.To exemplify this, you can apply a
Sleep(1000)
(just for the example) between function callsGenerate different keys since the seed will be different. (Date and Time)
As a solution you already received an answer, another would be to declare the variable
Random
at the class level and remove it from the methodCreatePassword
, you could also declare its Stringvalid
at the class level.And your method would be
The random function is not perfect. If you don't put a seed in it, it actually always rolls the same numbers.
To top it off, since you're initializing it every time you call it, it goes back to the beginning of the algorithm.
To add a seed to it, you need to call it as follows
This is a direct example of the MSDN, which clarifies that the algorithm to generate them is mathematical and the function is pseudo random.
Try adding something like this, and you should always get different keys.
Link to the MSDN in English
the class
Random
takes the CPU clock as its seed, so it generates pseudo-random numbers. I recommend you use the RNGCryptoServiceProvider class , which uses various elements of the Operating System as a seed generator to generate totally random numbers. Example