How to generate an HMAC in Java equivalent to a Python example?

HmacSHA1 seems to be the algorithm name you need:

SecretKeySpec keySpec = new SecretKeySpec(
        "qnscAdgRlkIhAUPY44oiexBKtQbGY0orf7OV1I50".getBytes(),
        "HmacSHA1");

Mac mac = Mac.getInstance("HmacSHA1");
mac.init(keySpec);
byte[] result = mac.doFinal("foo".getBytes());

BASE64Encoder encoder = new BASE64Encoder();
System.out.println(encoder.encode(result));

produces:

+3h2gpjf4xcynjCGU5lbdMBwGOc=

Note that I’ve used sun.misc.BASE64Encoder for a quick implementation here, but you should probably use something that doesn’t depend on the Sun JRE. The base64-encoder in Commons Codec would be a better choice, for example.

Leave a Comment