日期:2014-05-17 浏览次数:21192 次
因为我们这里要穷举的密码包括0-9,a-z,A-Z共62个字符,所以我们采用62进制来遍历。
首先,我们实现一个10进制转62进制的方法。
private static char[] charSet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray(); //private static string[] charSet = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", // "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" }; /// <summary> /// 将指定数字转换为指定长度的62进制 /// </summary> /// <param name="value">要转换的数字</param> /// <param name="length">需要的长度</param> /// <returns>62进制表示格式</returns> public static string ConvertTo62(long value, int length) { string sixtyNum = string.Empty; if (value < 62) { sixtyNum = charSet[value].ToString().PadLeft(length, '0'); } else { long result = value; //char[] ch = new char[length]; while (result > 0) { long val = result % 62; //ch[--length] = charSet[val]; sixtyNum = charSet[val] + sixtyNum; result = result / 62; } sixtyNum = sixtyNum.PadLeft(length, '0'); //for (int i = 0; i < length; i++) //{ // ch[i] = '0'; //} //sixtyNum = new string(ch); } return sixtyNum; }
Console.WriteLine(ConvertTo62(520, 5));//输出:0008o因为520转换成为62进制是8o,不足5位前面加0补齐。
然后,我们就可以写一个方法来遍历指定长度的密码了。
/// <summary> /// 遍历指定位数之间的所有组合 /// </summary> /// <param name="minLength">最短位数</param> /// <param name="maxLength">最长位数</param> public static void testPassword(int minLength, int maxLength) { for (int i = minLength; i <= maxLength; i++) { long maxNum = (long)Math.Pow(62, i); for (long j = 0; j < maxNum; j++) { Console.WriteLine(ConvertTo62(j, i));