变进制数的应用-穷举密码组合

  如果从0-9之间这10个数字里面挑选4个数字组成一个字符串(相临字符允许重复),其实就是0000,0001,0002......9999这10000种组合也就是10^4种组合。我当时想的就是如果把这0-9換成是任意字符在数组中对应的下标,那我就可以根据每位数字来确定对应的字符串是哪一个字符,并且每一种组合对应的每一位下标都可以计算出。结合平常所接触到的八进制与二进制,就可以扩大范围到任意进制数,同样也就可以将字符集扩大到所有可用字符的范围(需要注意计算时的溢出问题)
  



  其中“/"为取整运行,”%“为取余运算,”P^j“为P的j次方且优先级别最高。根据以上的计算与推测(个人使用EXCEL推算验证,这里没有列出)写出使用小写字母、大写字母和数字生成长度为8的所有密码组合算法如下(C#实现,不可直接运行):
using
System; using System.Collections.Generic; using System.IO, using System.Linq; using System.Text; using System.Threading.Tasks; namespace GeneratePassword { class GeneratePassword { private static double num; private char[] passwordChar = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; private int _pwdLen; public int pwdLen { get { return _pwdLen; } set { _pwdLen = value; } } public GeneratePassword(int passwordLength) { pwdLen = passwordLength; } public void Generate() { char[] arrDest = new char[pwdLen]; int temp; num = Math.Pow(passwordChar.Length, pwdLen); int passwordCharLen = passwordChar.Length; for (Int64 i = 0; i < num; i++) { for (int j = 0; j < pwdLen; j++ ) { //if (j == 0) //{ // temp = (int)(i % passwordCharLen); // arrDest[j] = passwordChar[temp]; //} //else //{ temp = (int)(Math.Floor(i / Math.Pow(passwordCharLen, j)) % passwordCharLen); arrDest[j] = passwordChar[temp]; //} } WriteFile.writeToFile(new string(arrDest)); } } } }

 

posted on 2014-04-03 17:51  似有若无  阅读(311)  评论(0编辑  收藏  举报