Random password generator

I am trying to write a random password generator. I am in the early stages and face several problems. With the code below and a screenshot, you can see that I am getting a very predictable string (a string of 2). Every time I get a string filled with only one number. How do I change my code to create a better password string? (other than including more 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; } 

}

+4
source share
4 answers

Just save random in 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 is seeded to almost one value every time you call charGen .

+5
source

The problem is that every time you call charGen you create a new Random , which is initialized with the current clock for the seed. Because they are created so quickly, they all receive the same seed.

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

+3
source

Why not use Rnd() instead of Random ?

 Private Function charGen() As Char Return Chr(Asc("0"c) + Rnd() * 10) End Function 

Then just call Randomize() before the loop.

+2
source

Source: https://habr.com/ru/post/1446853/


All Articles