c#不同的MD5实例导致哈希冲突

时间:2016-07-22 10:44:56

标签: c# hash md5

我有大约16,000,000个网址,我想得到关于网址的哈希码。 我使用System.Security.Cryptography.MD5创建哈希码,请参考this link

我的代码是这样的:

    private string createMD5(string input)
    {
            using(MD5 md5 = MD5.Create())//the problem is here
            {
                 byte[] inputBytes = System.Text.Encoding.Unicode.GetBytes(input);
                 byte[] hashBytes = md5.ComputeHash(inputBytes);

                 StringBuilder sb = new StringBuilder();
                 for(int i = 0;i < hashBytes.Length;i ++)
                 {
                     sb.Append(hashBytes[i].ToString("X2"));
                 }
                 return sb.ToString();
            }        
    }
    public void checkMD5Hash()
    {

        HashSet<string> urls = new HashSet<string>();
        using (StreamReader reader = new StreamReader(@"D:/ScopePractice/SatoriExtractionReport/TransformData/WikipediaUrlList.tsv"))
        {
            //calcuate the MD5 hashcode for all urls
            HashSet<string> set = new HashSet<string>();
            string line = null;
            while ((line = reader.ReadLine()) != null)
            {
                set.Add(createMD5(line));
            }
            double totalNum = 15844272;
            Console.WriteLine("MD5Hash: {0}",set.Count() * 1.0 / totalNum * 1.0);
        }
    }

我使用using(MD5 md5 = MD5.Create()),因此我创建了许多MD5实例,它会导致不同的url获得相同的MD5哈希码。

之后,我更改了我的代码,使用相同的MD5实例生成哈希码,问题就解决了。

    static MD5 md5 = MD5.Create();
    private string createMD5(string input)
    {

            byte[] inputBytes = System.Text.Encoding.Unicode.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes);

            StringBuilder sb = new StringBuilder();
            for(int i = 0;i < hashBytes.Length;i ++)
            {
                sb.Append(hashBytes[i].ToString("X2"));
            }
            return sb.ToString();



    }

但我不知道为什么不同的实例会导致这个问题,请帮助我,谢谢。

0 个答案:

没有答案