问题描述
我正在jmeter中建立一个测试计划,其中Sampler是一个HTTP POST请求。 我必须在请求正文中发送JSON有效负载。 现在,出于身份验证的目的,我必须使用一个秘密创建一个HMAC sha256代码,该秘密将在请求的标头中传递。 如何在预处理器脚本中创建HMAC?
解决方法
我之前做了以下类似的事情:
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