How can you generate the same MD5 Hashcode in C# and Java?

前端 未结 4 983
庸人自扰
庸人自扰 2020-12-08 01:29

I have a function that generates a MD5 hash in C# like this:

MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(data);
StringBuilder s         


        
4条回答
  •  广开言路
    2020-12-08 02:06

    I know this topic is old but I ran into the same issue just now and couldn't find an answer that worked for me. I was writing a patcher for a game and needed the md5 hashcode of files as a way to ensure that the files are up to date, but C# and Java gave me different strings although the files were identical.

    Here's how I solved it:

    C# Code:

    public static string getMD5(string fullPath)
    {
        MD5 md5 = MD5.Create();
        using (FileStream stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            byte[] hash = md5.ComputeHash(stream);
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < hash.Length; j++)
            {
                sb.Append(hash[j].ToString("X2"));
            }
            return sb.ToString();
        }
    }
    

    This creates a 32 character hex string. Apache Commons DigestUtils.md5Hex(InputStream) does the same, now the only different is that the C# example returns an uppercase string, so the solution is simply to convert the hash from the Java program to an uppercase string.

    Java code:

    public static String checkSumApacheCommons(String filePath)
    {
        String checksum = null;
        try 
        {  
             checksum = DigestUtils.md5Hex(new FileInputStream(filePath));
        }
        catch (IOException ex) 
        {
            ex.printStackTrace(System.out);
        }
        return checksum.toUpperCase();
    }
    

    The produced hashes look like F674865D8A44695A2443017CFA2B0C67.

    Hope this helps someone.

提交回复
热议问题