There are a number of examples online which show how to generate HMAC MD5 digests in Java.

Unfortunately, most of them don't generate digests which match the digest examples provided on the HMAC wikipedia page.

HMAC_MD5("key", "The quick brown fox jumps over the lazy dog") = 0x80070713463e7749b90c2dc24911e275
HMAC_SHA1("key", "The quick brown fox jumps over the lazy dog") = 0xde7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9
HMAC_SHA256("key", "The quick brown fox jumps over the lazy dog") = 0xf7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8

Here's a Java class which does. The trick is to do getBytes("ASCII") instead of UTF-8 (the default). Code courtesy of StackOverflow:

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
"The quick brown fox jumps over the lazy dog", "key", "HmacSHA1""UTF-8""ASCII"'0'
  • Mike Miller

    Very useful since I found out we need to protect our RESTful web service and a lot of posts seem to point to the method that Amazon uses, which is the hmac implementation.

    After reading some of posts about this method, they always talk about the public and private keys. Does the code above just take a short cut and create a secret key from the public api key or is the keyString passed in the 'secret key' and you just create a SecretKeySpec from it? I am bit fuzzy on that part?

  • Kelvin Tan

    Hey Mark, yeah, keyString is the secret key.

  • Mukima Mike

    Thanks a bunch Kelvin. This helped alot.

  • sid

    Thank you!!!

  • Dmitriy Kovanikov

    Man, this really helps me!!! I've browsed a lot of websites, but you solution does the thing :)

  • Archit Agarwal

    Thanks so much Kelvin, it looks very helpful and I am able to get the signature. I just have a question about msg string variable passing in the function.
    Is the value for this variable is fixed or can i use nonce and timestamp in this String variable. ? I am a bit confused at that part.

  • Bruno Marinho

    very good man!

  • Taylor O'Connor

    Thank you so much for this