I am setting up a test plan in jmeter in which a Sampler is an HTTP POST request. I have to send a JSON payload in the request body. Now, for authentication purposes, I have to create an HMAC sha256 code using a secret which will be passed in the header of the request. How can I create the HMAC in the preProcessor script?
1 Answers
0
votes
I've done something similar before with the following:
public static Mac SHARED_MAC;
static {
try {
SHARED_MAC = Mac.getInstance("HmacSHA256");
} catch (NoSuchAlgorithmException nsaEx) {
nsaEx.printStackTrace();
}
}
private String secretKey; // set this in a constructor or pass to the method below
public String generateSignature(String requestPath, String method, String body, String timestamp) {
try {
String prehash = timestamp + method.toUpperCase() + requestPath + body;
byte[] secretDecoded = Base64.getDecoder().decode(secretKey);
SecretKeySpec keyspec = new SecretKeySpec(secretDecoded, SHARED_MAC.getAlgorithm());
Mac sha256 = (Mac) SHARED_MAC.clone();
sha256.init(keyspec);
return Base64.getEncoder().encodeToString(sha256.doFinal(prehash.getBytes()));
} catch (CloneNotSupportedException | InvalidKeyException e) {
e.printStackTrace();
throw new RuntimeErrorException(new Error("failed")); // fatal error - exits program
}
}
HTH in some way