2

Im trying to get an MD5 with java and I receive a negative value. Can an MD5 result in a negative value?

This is my code:

        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] sigBytes = md5.digest((sharedSecret+"api_key"+API_KEY).getBytes());
        api_sig = new BigInteger(sigBytes).toString(16);

Thank You.

malana
  • 5,045
  • 3
  • 28
  • 41
Ari M
  • 1,386
  • 3
  • 18
  • 33

3 Answers3

3

new BigInteger(sigBytes) is interpreting your signature as a signed integer, so yes, it would be possible to get a negative number. If you want Your string to contain the hex representation of your md5 value, have a look at some of the answers here: How can I generate an MD5 hash?

Community
  • 1
  • 1
jbowes
  • 4,062
  • 22
  • 38
1

As jbowes alluded to, new BigInteger(sigBytes) is interpreting the signature as a signed integer (meaning the first bit denotes whether the number is positive or negative). If you want it to interpret the bytes as an unsigned number, you should use new BigInteger(1, sigBytes) instead.

Community
  • 1
  • 1
Gili
  • 86,244
  • 97
  • 390
  • 689
0

I use following method to get right MD5 hash String (and it never gave me "negative" value):

public static String createMD5Hash(String input) {
    try {
        MessageDigest m = MessageDigest.getInstance("MD5");
        byte[] out = m.digest(input.getBytes());
        return new String(Base64.encodeBase64(out));
    } catch (NoSuchAlgorithmException e) {
        return null;
    }
}

Note that Base64 is class from apache commons:

import org.apache.commons.codec.binary.Base64;
Břetislav Wajtr
  • 338
  • 1
  • 10