因為我們這裡要窮舉的密碼包括0-9,a-z,A-Z共62個字符,所以我們采用62進制來遍歷。
首先,我們實現一個10進制轉62進制的方法。
[csharp]
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;
}
進過測試發現把charSet定義成char類型比string的要快一點,但馬中的計算也采用char的方式(我注釋掉的代碼)也要快一點。
Console.WriteLine(ConvertTo62(520, 5));//輸出:0008o
因為520轉換成為62進制是8o,不足5位前面加0補齊。
然後,我們就可以寫一個方法來遍歷指定長度的密碼了。
[html]
/// <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));
}
}
}
調用:
testPassword(2, 3);
程序將會輸出2位和3位密碼的所有組合形式。(從:00-ZZZ)
根據這個思路,我們還可以寫出更多形式的窮舉算法。比如我們遍歷的密碼還包含小數點“.”,那麼我們只需要把算法改成63進制即可。