Generating SHA Mac Using Java

A team member was struggling to get this working recently, and noted that the examples he encountered on the Internet didn’t seem to be correct.

Heres the ‘working’ example that we have put in place – open to feedback if something silly is being done.

public static String generateHMac( String key, String baseString ) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {
SecretKeySpec secret = new SecretKeySpec(key.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secret);

byte[] resultArray = mac.doFinal(baseString.getBytes("UTF-8"));
byte[] hexBytes = new Hex().encode(resultArray);
return new String(hexBytes, "UTF-8");
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s