Jmeter經過beanshell對http消息進行簽名


1.增長前置beanshell腳本算法

clipboard.png

2.beanshell腳本要點shell

  • 經過引入外部jar包,引用相關簽名算法,如rsa、ecdsa等
  • 經過config.Arguments類的getArgument(0).getValue()獲取要發送請求的json body體。調用外部jar包方法進行sha等運算
  • http header的rmv和add操做

3.beanshell代碼樣例

import com.matrix.common.service.SignatureService;
import org.apache.jmeter.protocol.http.control.Header;
import org.apache.jmeter.config.Arguments;

//獲取簽名頭
public static String getSign(String contentSHA, String date,String nonce ){
    String privateKey = vars.get("privateKey");
    String method = "GET";
    String accept = vars.get("accept");
    String contentType = vars.get("contentType");
    String nonceHeader = "x-bfs-signature-nonce:"+nonce;
    String url = vars.get("createRfqOrderUrl");
    //調用jar包中SignatureService的sign方法進行進行簽名
    String signature = SignatureService.sign(privateKey,method,accept,contentSHA, contentType, date, nonceHeader, url);
    return  signature;
}

//發送請求前增長簽名相關的Header參數
public static void addHeaders( ){
    //增長日期頭
    String date = (new Date()).toString();
    sampler.getHeaderManager().removeHeaderNamed("Date");
    sampler.getHeaderManager().add(new Header("Date",date));
    //增長nonce頭
    String nonce = "550e8400e29b41d4a716446655440000";
    
    sampler.getHeaderManager().removeHeaderNamed("x-bfs-signature-nonce");
    sampler.getHeaderManager().add(new Header("x-bfs-signature-nonce",nonce));
    //經過getArgument方法獲取json body
    Arguments arguments = sampler.getArguments();
    String content = arguments.getArgument(0).getValue();
    log.info("content="+content);
    //增長Content-SHA256 頭
    String contentSHA =      SignatureService.getContentSHA256(content);
    log.info("contentSHA="+contentSHA);
    sampler.getHeaderManager().removeHeaderNamed("Content-SHA256");
    sampler.getHeaderManager().add(new Header("Content-SHA256",contentSHA));
    //增長簽名頭
    String signature = getSign(contentSHA,date,nonce);
    sampler.getHeaderManager().removeHeaderNamed("Authorization");
    sampler.getHeaderManager().add(new Header("Authorization","bfs "+ vars.get("accessKeyId") +":"+signature));
    return;
}

addHeaders();
相關文章
相關標籤/搜索