JMeter Parameter Signature - Groovy Tool Class Form

Posted by miasma on Fri, 24 Apr 2020 04:30:03 +0200

How do I sign parameters in JMeter?

Last Period JMeter Parameter Signature - Groovy Script Form Using Groovy scripting, this issue continues Groovy's use of parameter signatures in JMeter -- parameter signatures are done using Groovy tool classes.

This is a common situation in interface testing where one parameter of the interface is determined by other parameters, including the check token, and in my experience, it is common in PHP back-end services.Here's how to handle this situation with the Groovy tool class.Code is provided by development, just copy it, and that's one reason I chose Groovy: near perfect compatibility with Java.The Groovy script content in the code is consistent with the previous period and key information is omitted.

  • First create a new simple thread group and a simple request:

  • Add JSR223 Preprocessor

Script content:

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

vars.put("MY1","flow")
props.put("MY","ewewewerr")
log.info(props.get("MY"))
sampler.addArgument("name","funteddster")
sampler.addArgument("pwd","funtddester")

def args = sampler.getArguments()
def ss = [:]
log.info(sampler.getArguments().toString())
args.getArgumentCount().times{
	def a = args.getArgument(it)
	ss.put(a.ARG_NAME,a.VALUE)
}

def my_var = RSAUtilLJT.sign(ss,RSAUtilLJT.getPrivateKey(RSAUtilLJT.RSA_PRIVATE_KEY)) as String;

log.warn "Output parameters-------- ${vars} console"
log.info("222222 " + my_var);

sampler.addArgument("sign", my_var)



public class RSAUtilLJT {

    /**
     * RSA Maximum Encrypted Clear Text Size
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA Maximum decrypted ciphertext size
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * RSA private key
     */
    public static final String RSA_PRIVATE_KEY= "Confidential Content";
    /**
     * RSA public key
     */
    public static final String RSA_PUBLIC_KEY= "Confidential Content";

    /**
     * Do not participate in signature parameters
     */
    private static final String excludeKey = "sign";


    /**
     * Get Private Key
     *
     * @param privateKey Private key string
     * @return
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * Get Public Key
     *
     * @param publicKey Public key string
     * @return
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * RSA encryption
     *
     * @param data Data to be encrypted
     * @param publicKey public key
     * @return
     */
    public static String encrypt(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // Sectioned Encryption of Data
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        // Get encrypted content encoded using base64 and converted to string using UTF-8 as standard
        // Encrypted string
        return new String(Base64.encodeBase64String(encryptedData));
    }

    /**
     * RSA Decrypt
     *
     * @param data Data to be decrypted
     * @param privateKey private key
     * @return
     */
    public static String decrypt(String data, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] dataBytes = Base64.decodeBase64(data);
        int inputLen = dataBytes.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // Decrypt data by segments
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        // Decrypted content
        return new String(decryptedData, "UTF-8");
    }

    /**
     * autograph
     *
     * @param data Data to be signed
     * @param privateKey private key
     * @return autograph
     */
    public static String sign(String data, PrivateKey privateKey) throws Exception {
        byte[] keyBytes = privateKey.getEncoded();
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey key = keyFactory.generatePrivate(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(key);
        signature.update(data.getBytes());
        return new String(Base64.encodeBase64(signature.sign()));
    }

    /**
     * Verify Signature
     *
     * @param srcData Original string
     * @param publicKey public key
     * @param sign autograph
     * @return Is Check Signature Passed
     */
    public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
        byte[] keyBytes = publicKey.getEncoded();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey key = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initVerify(key);
        signature.update(srcData.getBytes());
        return signature.verify(Base64.decodeBase64(sign.getBytes()));
    }

    /**
     * Sign map
     * @param mapData
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static String sign(Map<String, String> mapData, PrivateKey privateKey) throws Exception {
        return sign(getStr(mapData), privateKey);
    }

    /**
     * Signature Verification
     * @param mapData Parameter map
     * @param publicKey public key
     * @return
     * @throws Exception
     */
    public static boolean verify(Map<String, String> mapData, PublicKey publicKey) throws Exception {
        String sign = mapData.remove(excludeKey);
        if (sign == null || sign.length() < 1) {
            throw new RuntimeException("Parameter missing signature");
        }
        return verify(getStr(mapData), publicKey, sign);
    }

    /**
     * Interface Request Parameter To String
     * @param parms
     * @return
     */
    public static String getStr(Map<String, String> parms) {
        parms.remove(excludeKey);
        TreeMap<String, String> sortParms = new TreeMap<>();
        sortParms.putAll(parms);
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, String> entry : parms.entrySet()) {
            builder.append(entry.getKey());
            builder.append("=");
            builder.append(String.valueOf(entry.getValue()));
            builder.append("&");
        }
        if (builder.length() > 1) {
            builder.setLength(builder.length() - 1);
        }
        return builder.toString();
    }
}
  • Console Output:
2020-04-17 17:13:30,989 INFO o.a.j.e.StandardJMeterEngine: Running the test!
2020-04-17 17:13:30,991 INFO o.a.j.s.SampleEvent: List of sample_variables: []
2020-04-17 17:13:31,008 INFO o.a.j.g.u.JMeterMenuBar: setRunning(true, *local*)
2020-04-17 17:13:31,208 INFO o.a.j.e.StandardJMeterEngine: Starting ThreadGroup: 1 : Thread Group
2020-04-17 17:13:31,208 INFO o.a.j.e.StandardJMeterEngine: Starting 1 threads for group Thread Group.
2020-04-17 17:13:31,208 INFO o.a.j.e.StandardJMeterEngine: Thread will continue on error
2020-04-17 17:13:31,209 INFO o.a.j.t.ThreadGroup: Starting thread group... number=1 threads=1 ramp-up=0 perThread=0.0 delayedStart=false
2020-04-17 17:13:31,210 INFO o.a.j.t.ThreadGroup: Started thread group number 1
2020-04-17 17:13:31,213 INFO o.a.j.e.StandardJMeterEngine: All thread groups have been started
2020-04-17 17:13:31,216 INFO o.a.j.t.JMeterThread: Thread started: Thread Group 1-1
2020-04-17 17:13:31,337 INFO o.a.j.m.J.JSR223 Parameter Signature Groovy class: ewewewerr
2020-04-17 17:13:31,341 INFO o.a.j.m.J.JSR223 Parameter Signature Groovy class: t=flow()&s=ewewewerr()&name=funteddster()&pwd=funtddester()
2020-04-17 17:13:31,360 WARN o.a.j.m.J.JSR223 Parameter Signature Groovy class: Output parameters-------- org.apache.jmeter.threads.JMeterVariables@7bdab282 console
2020-04-17 17:13:31,361 INFO o.a.j.m.J.JSR223 Parameter Signature Groovy class: 222222 DV1UC0RF7y7FWArtYJP8LaUYwWZm7Mc5P8vmx5e4cGqQstaW3LlfR+o5mSiBTTxLY3NSvsr5EHLkLzPcfJ3YCmjJnneZj+lCb7fR7XA5snwGHJNbeDejn6x3oNVEZF8i4MR/vPO9I1lawA6pEuO5t7kW21IizQdEyxAc2pxLcj8=
2020-04-17 17:13:31,495 INFO o.a.j.t.JMeterThread: Thread is done: Thread Group 1-1
2020-04-17 17:13:31,495 INFO o.a.j.t.JMeterThread: Thread finished: Thread Group 1-1
2020-04-17 17:13:31,495 INFO o.a.j.e.StandardJMeterEngine: Notifying test listeners of end of test
2020-04-17 17:13:31,495 INFO o.a.j.g.u.JMeterMenuBar: setRunning(false, *local*)


  • View the result tree

  • You can clearly see that the signature field sign is already written into the parameter.
  • Solemnly declare that "FunTester" is the first one. Welcome to the communication and prohibit third-party reprinting.

I found that JMeter series has written a lot of articles, just the whole set of enhanced versions, and the rest of Demo has also been published, the old text is as follows:

Topics: Programming Java Apache PHP codec