Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Password Generator

I am attempting to write a random password generator. I am in the early stages and am running into a few problems. With the below code and screenshot you can see that I get a very predictable string (the string of 2's). Every time I receive a string filled with only one kind of number. How should I edit my code to generate a better password string? (other than including more than just numbers)

enter image description here

private void button1_Click(object sender, EventArgs e)
{
    int characters = Convert.ToInt32(comboBox1.SelectedIndex);
    string password = "";

    for(int i = 0; i <= characters; i++)
    {
       password = password +charGen();
    }

    label2.Text = password;
}

private char charGen()
{
    Random random = new Random();
    char randomNumber = Convert.ToChar( random.Next(48, 57));
    return randomNumber;
}

}

like image 241
jth41 Avatar asked Dec 20 '22 13:12

jth41


2 Answers

Just keep the random in the class scope:

Random random = new Random();

private void button1_Click(object sender, EventArgs e)
{
    int characters = Convert.ToInt32(comboBox1.SelectedIndex);
    string password = "";

    for(int i = 0; i <= characters; i++)
    {
       password = password +charGen();
    }

    label2.Text = password;
}

private char charGen()
{
    char randomNumber = Convert.ToChar( random.Next(48, 57));
    return randomNumber;
}

Currently it's seeded to practically the same value each time you call charGen.

like image 185
Serge Belov Avatar answered Dec 29 '22 00:12

Serge Belov


The problem is that each time charGen is called, you create a new Random, which is initialized with the current clock for a seed. Since they are created so quickly, they all get the same seed.

You should create a single Random object at class level (or pass it to charGen).

like image 28
Blorgbeard Avatar answered Dec 29 '22 00:12

Blorgbeard