MD5散列的奇怪行为

时间:2010-10-14 06:33:48

标签: c# .net hash

我遇到了以下代码的一个问题,下面的代码假设在一次迭代后停止,但它只是继续。但是,如果我删除最后一个“result_bytes = md5.ComputeHash(orig_bytes);”然后它会工作。有没有人面临类似的问题?

MD5 md5;
            byte[] orig_bytes;
            byte[] result_bytes;
            Dictionary<byte[], string> hashes = new Dictionary<byte[], string>();

            string input = "NEW YORK";
            result_bytes = UnicodeEncoding.Default.GetBytes("HELLO");
 while (!hashes.ContainsKey(result_bytes))
            {
                md5 = new MD5CryptoServiceProvider();
                orig_bytes = UnicodeEncoding.Default.GetBytes(input);
                result_bytes = md5.ComputeHash(orig_bytes);

                hashes.Add(result_bytes, input);
                Console.WriteLine(BitConverter.ToString(result_bytes));
                Console.WriteLine(hashes.ContainsKey(result_bytes));

                result_bytes = md5.ComputeHash(orig_bytes);
            }

2 个答案:

答案 0 :(得分:2)

当你将result_bytes重新分配给最后一行中的新值时,你有一个对字节数组的新引用,它不等于集合中的那个,因此hashes.ContainsKey返回false。

答案 1 :(得分:2)

您假设字节数组覆盖EqualsGetHashCode以进行相等性比较:它们不会。他们只是使用默认的身份测试 - 所以如果没有最后的额外任务,你只需要检查你刚刚添加的确切关键对象是否仍然在字典中 - 这当然是。

这样做的一种方法是存储散列的可逆字符串表示(例如,使用base64),而不是散列本身。或者编写自己的IEqualityComparer<byte[]>实现并将其传递给Dictionary构造函数,以便它使用该实现来查找字节数组的哈希码并将它们相互比较。

简而言之:这与MD5无关,而且与

这一事实有关
Console.WriteLine(new byte[0].Equals(new byte[0]));

将打印错误:)