HMAC and SHA256 in JMeter

Some projects require authentication features that involve some quite intricate steps. But fret not, in JMeter we can use Groovy to do the heavy lifting. Below is a very simple example of how you can do a HMAC encryption. It also includes the SHA256 hashing and base64 encoding. The only thing missing are the functions to read the variables from JMeter and publish the hash to JMeter but that is trivial and you can fit it into whatever you already have scripted.

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

String secretKey = "secret";
String data   = "Message";

Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256");
byte[] digest = mac.doFinal(data.getBytes());
encodedData = digest.encodeBase64().toString();"HMAC SHA256 base64: " + encodedData);

by Oliver Erlewein


3 thoughts on “HMAC and SHA256 in JMeter

  1. Thanks for the cool solution. I would recommend to remove mentioning of Beanshell as

    1. It doesn’t provide possibility to directly perform Base64 encoding on the byte array
    2. It has some performance problems

    Also JMeter comes with Apache’s commons-codec library so HmacUtils class could be used.

    • Hi,
      Yes I din’t test on BeanShell. Thanks for pointing that out. Is now removed.
      As for performance…yeah…just better to use Groovy.

  2. Whaaat, I just needed this for the first time in my life, did a quick google, and the very first link is to your page! Much obliged, Oliver. 🙂

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s