1

My code to generate md5 looks like

@Nonnull
static String getAuthCode(@Nonnull final String email, @Nonnull final String memberExternalId,
                          @Nonnull final String clientId, @Nonnull final String clientSecret) {
    final MessageDigest messageDigest = getMessageDigest("MD5");
    final String stringForHashCode = email + ":" + memberExternalId + ":" + clientId + ":" + clientSecret;
    messageDigest.update(stringForHashCode.getBytes());
    return new BigInteger(1, messageDigest.digest()).toString();
}

I run the test as

@Test
public void test() {
    System.out.println(getAuthCode("a", "b", "c", "d"));
}

and I get the output as

306937959255909402080036399104389354327

When I run the same test on online website, I get the output as

e6ea19c62a3763c7b78c475652c51357 

for same input a:b:c:d

Question

  • Why are they different?
  • How can I get the output similar to what I get online? which is e6ea19c62a3763c7b78c475652c51357?
3
  • 3
    messageDigest.update(stringForHashCode.getBytes()); <-- this will use the default JVM encoding. Is that what you want? Rule of thumb: always specify the encoding! Commented Jan 1, 2015 at 20:49
  • Not sure what encoding will give me result similar to what I get online Commented Jan 1, 2015 at 20:51
  • I even tried messageDigest.update(stringForHashCode.getBytes(Charset.forName("UTF-8"))); but the result is still the same Commented Jan 1, 2015 at 20:53

1 Answer 1

3

The problem pointed out in comments is a problem - you should define which encoding you want to use. I'd recommend using UTF-8, e.g.

messageDigest.update(stringForHashCode.getBytes(StandardCharsets.UTF_8));

A bigger problem, however, is that you're printing out a BigInteger created from the digest - which is printing it out in decimal. The result you're getting from the online tool is in hexadecimal instead.

While you could convert the BigInteger into hex, I would personally avoid creating a BigInteger in the first place - you'd need to work out padding etc. Instead, just use one of the many libraries available for converting a byte[] to hex, e.g. Apache Commons Codec with its Hex class.

Sign up to request clarification or add additional context in comments.

1 Comment

Guava's Hashing.md5().hashString(str, UTF_8).toString() also prints out hex.

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.