简体   繁体   中英

generating a batch of random passwords

Generating a random password is easy. but generating a batch is more difficult.

    public static string getRandomPassword(int letters, int getallen) {
        //int letters = 8;
        //int getallen = 5;

        char[] letterdeel = new char[letters];
        int minGetal = (int)Math.Pow(10, getallen - 1);
        int maxGetal = (int)Math.Pow(10, getallen);

        string password;
        Random r = new Random();
        int test = (int)(DateTime.Now.Ticks);
        for (int i = 0; i < letters; i++) {
            r = new Random((int)(DateTime.Now.Ticks) + i);
            bool capital = r.Next(2) == 0 ? true : false;
            if (capital) {
                letterdeel[i] = (char)r.Next(65, 91);
            } else {
                letterdeel[i] = (char)r.Next(97, 123);
            }
        }

        password = new string(letterdeel);
        password += r.Next(minGetal, maxGetal);

        return password;
    }

this is my method, the passwords should be in a certain letter-number format. this works fine, however if i have a for loop pulling 100 passwords from this method, in my array i have 5-8 the same passwords, then again 5-8 the same pass.

i know WHY this is, because of the random function and the clock it depends on, but how do i fix this?

Move Random r to outside the method if you are repeatedly calling it. You are going to be hitting it several times in the same relative timeframe, so you are going to be generating the same seeds. You also want to get rid of the line below. It is unnecessary, and (again), with the nature of DateTime.Now , you would just continue to generate the same sequence of "random" numbers.

r = new Random((int)(DateTime.Now.Ticks) + i); 

Define your random number generator as a static outside of the function.

How can I get true randomness in this class without Thread.Sleep(300)?

使用集合而不是存储在其中的任何集合,不要循环100次,直到集合中包含100个项目为止。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM