P验签

import org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy
import org.apache.jmeter.protocol.http.control.HeaderManager
import org.apache.jmeter.protocol.http.control.Header
import org.apache.jmeter.protocol.http.util.HTTPArgument
import java.net.URL
import java.net.URLEncoder
import java.net.URLDecoder
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import org.apache.commons.codec.binary.Base64
import java.util.ArrayList
import java.util.Collections

// ====================== ParamUtils ======================
class ParamUtils {
    ArrayList<String> values = new ArrayList<String>()
    long timestamp

    ParamUtils(long timestamp) {
        this.timestamp = timestamp
    }

    void put(String k, String v) throws Exception {
        if (!k || k.isEmpty()) return
        String value = URLEncoder.encode(v ?: "", "UTF-8")
        values.add(k + "=" + value)
    }

    void addGetParams(ArrayList<String> params) throws Exception {
        for (String param : params) {
            String[] kv = param.split("=", 2)
            put(kv[0], kv.length > 1 ? kv[1] : "")
        }
        Collections.sort(values)
    }

    String getParams(String requestMethod, String requestBody, String queryString) throws Exception {
        values.clear()
        if ("GET".equalsIgnoreCase(requestMethod)) {
            ArrayList<String> paramList = new ArrayList<>()
            if (queryString) {
                String[] pairs = queryString.split("&")
                for (String pair : pairs) {
                    int idx = pair.indexOf("=")
                    String k = URLDecoder.decode(pair.substring(0, idx), "UTF-8")
                    String v = idx > 0 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : ""
                    put(k, v)
                }
            }
            put("signTimestamp", String.valueOf(timestamp))
            addGetParams(paramList)
        } else if (["POST", "PUT", "DELETE"].contains(requestMethod.toUpperCase())) {
            if (requestBody) {
                values.add("requestBody=" + requestBody.replaceAll("\\r|\\n", ""))
            }
            put("signTimestamp", String.valueOf(timestamp))
        }
        return String.join("&", values)
    }
}

// ====================== 主逻辑 ======================
if (!(sampler instanceof HTTPSamplerProxy)) {
    log.warn("Sampler is not an instance of HTTPSamplerProxy.")
    return
}

HTTPSamplerProxy httpSampler = (HTTPSamplerProxy) sampler
String apiKey = "8GN81BP6-OMDZVGHQ-***"
String secretKey = "1871de648d06079b***886e5346964674b16724084ac4e"
long timestamp = System.currentTimeMillis()
String requestMethod = httpSampler.getMethod()
URL urlObj = httpSampler.getUrl()
String urlPath = urlObj.getPath()
String queryString = urlObj.getQuery()

// 获取 POST body
String actualRequestBody = ""
if (!"GET".equalsIgnoreCase(requestMethod)) {
    if (httpSampler.getPostBodyRaw()) {
        actualRequestBody = httpSampler.getArguments().getArgument(0).getValue()
    } else {
        StringBuilder sb = new StringBuilder()
        for (HTTPArgument arg : (ArrayList<HTTPArgument>) httpSampler.getArguments().getArguments()) {
            if (sb.length() > 0) sb.append("&")
            sb.append(URLEncoder.encode(arg.getName(), "UTF-8"))
            sb.append("=")
            sb.append(URLEncoder.encode(arg.getValue(), "UTF-8"))
        }
        actualRequestBody = sb.toString()
    }
}

// 计算签名
ParamUtils paramUtils = new ParamUtils(timestamp)
String paramValue = paramUtils.getParams(requestMethod, actualRequestBody, queryString)
String payload = requestMethod.toUpperCase() + "\n" + urlPath + "\n" + paramValue

try {
    Mac mac = Mac.getInstance("HmacSHA256")
    SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA256")
    mac.init(secretKeySpec)
    String signature = Base64.encodeBase64String(mac.doFinal(payload.getBytes("UTF-8")))

    vars.put("signature", signature)
    vars.put("signTimestamp", String.valueOf(timestamp))
    vars.put("requestBody", actualRequestBody)

    // 设置 Headers
    if (!httpSampler.getHeaderManager()) httpSampler.setHeaderManager(new HeaderManager())
    httpSampler.getHeaderManager().clear()
    httpSampler.getHeaderManager().add(new Header("key", apiKey))
    httpSampler.getHeaderManager().add(new Header("signature", signature))
    httpSampler.getHeaderManager().add(new Header("signTimestamp", String.valueOf(timestamp)))
    httpSampler.getHeaderManager().add(new Header("Content-Type", "application/json"))

    // 输出调试信息
    log.info("========== [DEBUG] ==========")
    log.info("URL: " + urlObj)
    log.info("Method: " + requestMethod)
    log.info("payload: " + payload)
    log.info("signature: " + signature)
    log.info("requestBody: " + actualRequestBody)
} catch (Exception e) {
    log.error("Error generating signature: " + e.getMessage(), e)
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容