2010-09-28 119 views
1

生成随机密码很容易。但生成批次更困难。生成一批随机密码

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; 
    } 

这是我的方法,密码应该是在一定的字母数字格式。 这工作正常,但是如果我有一个for循环从这个方法拉100个密码,在我的数组中我有5-8相同的密码,然后再次5-8相同的通行证。

我知道这是为什么,因为随机函数和它依赖的时钟,但我该如何解决这个问题?

回答

0

使用一个集合而不是你存储的任何集合,并且不循环100次,但直到集合中有100个项目。

5

Random r移到方法外部,如果您反复调用它。你会在相同的相对时间内多次击中它,所以你将会生成相同的种子。你也想摆脱下面的线。这是不必要的,并且(再次)with the nature of DateTime.Now,您只需继续生成相同序列的“随机”数字。

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

这就是为什么我接着说:i'它。把它放在外面确实是最好的选择。 – Stefanvds 2010-09-28 17:15:15

+0

是的,但作为解释,添加'i'仍然导致相同的种子和序列。考虑到'DateTime.Now'会通过几个方法调用而保持不变。比方说,例如,为了参数的缘故,第一次方法调用时DateTime.Now.Ticks为0。对于这种方法的第一次执行,它会发生得如此之快,以至于DateTime.Now没有更新为新值(请参阅博客文章)。所以你的循环内部的方法总是会经过0,1,2,3,4等等。方法每次执行的相同种子,Random对象产生的相同序列。 – 2010-09-28 17:24:10