0

I have got to make the same function in Java and C#, but the result are not the same.

My code in C# :

    string xmlString = System.IO.File.ReadAllText(@"crc.xml");

    byte[] bytes = Encoding.ASCII.GetBytes(xmlString);

    // step 1, calculate MD5 hash from input
    MD5 md5 = System.Security.Cryptography.MD5.Create();
           
    byte[] hash = md5.ComputeHash(bytes);

    // step 2, convert byte array to hex string
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < hash.Length; i++)
    {
         sb.Append(hash[i].ToString("X2"));
    }
    Console.WriteLine(sb.ToString());

And my code in Java :

    string xmlstring = Files.readString(Paths.get("crc.xml"));
    MessageDigest m = MessageDigest.getInstance("MD5");
    byte[] digest = m.digest(xmlstring.getbytes());
    String hash = new BigInteger(1, digest).toString(16);
    System.out.println(hash);

In C# I have this result :

F5F8B2F361FEA6EA30F24BEBAA5BDE3A

But in Java I have this result :

8fb40aad49fbf796b82a2faa11cda764

What I'm doing wrong?

4
  • I think the C# byte is unsigned and the java byte is signed, that can cause the difference Commented Oct 12, 2020 at 14:13
  • 6
    C# is using Encoding.ASCII but Java uses UTF-8 Commented Oct 12, 2020 at 14:13
  • 7
    If you want to calculate the MD5 of a file, you should never read the file content into a String, because that already includes a level of interpretation (namely decoding the charset) that is not necessary and can be actively harmful to the attempt. Just read the byte[] directly (or even better, stream the byte[] data, because there's no reason to have it all in memory at once). In Java the direct replacement would be Files.readAllBytes(). It seems .NET has a ReadAllBytes as well. Commented Oct 12, 2020 at 14:16
  • (the only reason I didn't post this as an answer is that I'm not sure that this is the specific reason for the difference here, but it is definitely an issue here). Commented Oct 12, 2020 at 14:23

1 Answer 1

1

Codebrane say it. Use

byte[] bytes = Encoding.UFT8.GetBytes(xmlString);

instead of

byte[] bytes = Encoding.ASCII.GetBytes(xmlString);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.