Because the password we want to raise here includes 0-9, a-z, A-Z a total of 62 characters, so we use 62 to traverse.
First, we implement a 10-to-62 conversion method.
[Csharp]
Private static char [] charSet = "0123456789 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ". 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>
/// Convert a specified number to a 62-digit value of the specified length
/// </Summary>
/// <Param name = "value"> number to be converted </param>
/// <Param name = "length"> required length </param>
/// <Returns> 62 hexadecimal representation </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;
}
After testing, we found that defining charSet as a char type is faster than that of string type, but the calculation in the horse also adopts the char method (the code I commented out.
Console. WriteLine (ConvertTo62 (520, 5); // output: 0008o
Because 520 is converted to 62 in 8o format, less than 5 digits are filled with 0.
Then, we can write a method to traverse the password of the specified length.
[Html]
/// <Summary>
/// Traverse all combinations between the specified digits
/// </Summary>
/// <Param name = "minLength"> Minimum number of digits </param>
/// <Param name = "maxLength"> maximum number of digits </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 ));
}
}
}
Call:
TestPassword (2, 3 );
The program will output all the combinations of two and three passwords. (From: 00-ZZZ)
Based on this idea, we can also write more forms of exhaustive algorithms. For example, if the password we traverse also contains the decimal point ".", we only need to change the algorithm to the 63 hexadecimal format.