How to get unsigned md5 hash in Java

2020-08-05 10:31发布

问题:

I am using consuming a C# web services and one of the parameters is sending a md5 hash. Java creates MD5 hash with signed (contains negative number in the byte array) and C# generates unsigned (contains no negative number in the byte array).

I have gone through multiple similar question in Stack Overflow but did not find any to my satisfaction.

All I need is unsigned byte array similar to the one c# generates. I have tried using BigInteger but I need it in an unsigned byte array since I need do further processing after that. BigInteger gives me one single integer and using tobytearray() still has negative numbers.

If I have to do 2 complement, then how can I do that. Then I can loop through the byte array and convert negative number to positive number.

I am using the following Java code for generating MD5 hash:

    String text = "abc";
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] md5hash = new byte[32];
    try {
        md.update(text.getBytes("utf-8"), 0, text.length());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    md5hash = md.digest();  

回答1:

Java bytes are signed numbers, but that only means that when considering a byte (which is a sequence of 8 bits) as a number, Java treats one of the bits as a sign bit, whereas other language read the same sequence of bits as an unsigned number, containing no sign bit.

The MD5 algorithm is a binary algorithm that transforms a sequence of bits (or bytes) into another sequence of bits (or bytes). The way Java does that is the same as the way any other language does it. It's only when displaying the bytes as numbers that you'll get different outputs depending on the way the language transforms bytes into numbers.

So the short answer is, send an MD5 hash generated using Java to a C# program, and it will work fine.

If you want to display the byte array in Java as unsigned numbers, just use the following code:

for (byte b : bytes) {
    System.out.println(b & 0xFF);
}


标签: java md5