C#通过n层循环进行字符组合实现暴力破解MD5
自动根据待解密的MD5字符串长度,进行处理。
static class Program
{/// <summary>/// 应用程序的主入口点。/// </summary>[STAThread]static void Main(){string[] plainArray = "0,1,2,3,4,5,6,7,8,9"; //可疑字符串string cipherStr = "202CB962AC59075B964B07152D234B70"; // 待解密MD5字符串,32位//string cipherStr = "AC59075B964B0715"; // 待解密MD5字符串,16位int n = 6; // 明文长度bool isDecried = false;string plainStr = MD5Decrypt(plainArray, n, cipherStr, ref isDecried);if (isDecried){Console.WriteLine(plainStr);}else{Console.WriteLine("解密失败,明文不在可疑明文字符组合中!");}}/// <summary>/// MD5解密/// </summary>/// <param name="plainArray">可疑明文字符数组</param>/// <param name="n">明文长度</param>/// <param name="cipherStr">待解密的密文</param>/// <param name="isDecried">是否已完成解密</param>/// <returns>解密后的明文</returns>private string MD5Decrypt(string[] plainArray, int n, string cipherStr, ref bool isDecried){List<string[]> list = new List<string[]>();for (int i = 0; i < n; i++){list.Add(plainArray);}string plainStr = "";MD5 md5 = MD5.Create();MD5Combination(0, list, md5, cipherStr, "", ref plainStr, ref isDecried);return plainStr;}/// <summary>/// MD5解密(迭代实现 N 层字符组合,对组合字符串进行MD5后和密文进行比对)/// </summary>/// <param name="index">N层明文字符串集合的索引</param>/// <param name="matrix">N层明文字符串集合</param>/// <param name="md5">MD5对象,避免重复创建对象导致内存溢出</param>/// <param name="cipherStr">待解密的密文</param>/// <param name="str">组合字符串</param>/// <param name="plainStr">解密后的明文</param>/// <param name="isDecried">是否已完成解密</param>private void MD5Combination(int index, List<string[]> matrix, MD5 md5, string cipherStr, string str, ref string plainStr, ref bool isDecried){for (int k = 0; k < matrix[index].Length; ++k){if (isDecried){return;}string charStr = matrix[index][k];String tempStr = str + charStr;string encryStr = "";switch (cipherStr.Length){case 16:encryStr = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(tempStr)), 4, 8).Replace("-", "");break;case 32:encryStr = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(tempStr))).Replace("-", "");break;}if (encryStr == cipherStr || encryStr.ToLower() == cipherStr){plainStr = tempStr;isDecried = true;return;}else if (index < matrix.Count - 1){MD5Combination(index + 1, matrix, md5, cipherStr, tempStr, ref plainStr, ref isDecried); // 向下传递的逻辑}}return;}
}