Skip to main content
 首页 » 编程设计

c#之MD5 散列的奇怪行为

2024年02月24日21zhoujg

我在使用以下代码时遇到了一个奇怪的问题,下面的代码假设在一次迭代后停止,但它只是继续运行。但是,如果我删除最后一个“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); 
            } 

请您参考如下方法:

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