Gen HMAC (Oauth) ID in JAVA

Not applicable

We have a GROOVY script (from Apigee) that generates a Message Authentication Code (MAC) for our REST APIs. This works fine for soapUI functionality testing but now we are load testing using JMETER and need to generate the MAC ID in JAVA. Has anyone tested HMAC + a REST API in JMETER? or does anyone have a corresponding JAVA code for the Groovy Script.

0 1 1,037
1 REPLY 1

I don't know the Groovy script you refer to.

But, HMAC is a well known approach.

Implementing it in Java is pretty simple:

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.binary.Base64;

...


Mac hmac = Mac.getInstance(javaizedAlg);
SecretKeySpec key = new SecretKeySpec(signingKey.getBytes(), javaizedAlg);
hmac.init(key);
byte[] hmacBytes = hmac.doFinal(stringToSign.getBytes("UTF-8"));
String sigHex = Hex.encodeHexString(hmacBytes);
String sigB64 = Base64.encodeBase64String(hmacBytes); 

This snip is taken from working code (with all the required imports, etc) that you can find here.

I am not sure where OAuth comes into play, for your question. Is this OAuth v1.0a ?

If so, I would recommend not using HMAC directly, but instead relying on one of the libraries that computes OAuth 1.0a signatures. The problem with OAuth1.0a is that there are particular rules about how to format the string-to-sign, and if you mis-apply any of those rules, the signature will not be correct. Also, similar rules about how to format the final header. Because of all those rules, it's better to rely on an implementation that has already been built. Here is some example code, but you can Google around for "Java OAuth1.0a signature" for more.