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; import java.security.InvalidKeyException; String secretKey = "secret"; String data = "Message"; Mac mac = Mac.getInstance("HmacSHA256"); SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256"); mac.init(secretKeySpec); byte digest = mac.doFinal(data.getBytes()); encodedData = digest.encodeBase64().toString(); log.info("HMAC SHA256 base64: " + encodedData);
by Oliver Erlewein
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.
Yes I din’t test on BeanShell. Thanks for pointing that out. Is now removed.
As for performance…yeah…just better to use Groovy.
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. 🙂