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

前端 未结 4 975
庸人自扰
庸人自扰 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 01:57

    That should be fine - although you could make the Java code simpler by just calling

    byte[] digest = m.digest(bytes);
    

    instead of calling update then digest.

    Are you absolutely sure you've got the same data in both cases? Could you post sample programs showing this failing with the same hard-coded data?

    EDIT: Here's the sort of test I was thinking of. These two programs give the same result:

    C#:

    using System;
    using System.Security.Cryptography;
    using System.Text;
    
    class Test
    {
        static void Main()
        {
            byte[] bytes = { 0x35, 0x24, 0x76, 0x12 };
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(bytes);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("x2"));
            }
            Console.WriteLine(sb);
        }
    }
    

    Java:

    import java.math.BigInteger;
    import java.security.MessageDigest;
    
    public class Test
    {
        public static void main(String[] args) throws Exception
        {
            byte[] bytes = { 0x35, 0x24, 0x76, 0x12 };
            MessageDigest m = MessageDigest.getInstance("MD5");
            byte[] digest = m.digest(bytes);
            String hash = new BigInteger(1, digest).toString(16);
            System.out.println(hash);
        }
    }
    

提交回复
热议问题