接口测试 问:jmeter 是否有方式能实现接口批量加解密功能?

未来来 · 2020年05月12日 · 最后由 RhettXia 回复于 2020年06月06日 · 1788 次阅读

在使用 jmeter 做接口测试时,通常会遇到一种场景,一批接口测试的脚本,加解密的方式是一致的,目前采用的笨方法就是每个接口都复制一遍加解密的 bean shell 组件。
目前是否有方法能解决批量接口使用同一个加解密组件?或者详细抽象的方法

共收到 4 条回复 时间 点赞
5楼 已删除

pre/postProcessor 的作用域,是所有的子组件 sample

必须你做二次开发:
beanshell 写脚本的方式,或者用 jsr233 相关组件用你熟悉的语言 (groovy,或者 java) 去实现;
jmeter 只是一个工具而已,不可能方方面面都帮你来做
至于在哪个阶段用,就看你是在发请求前还是发请求后,反正每个阶段都有对应的组件给你用

把加密写好打成 jar 包,导入后 jmeter 可以直接调用
举个栗子

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class EncryptUtil {
    // 加密
    public static String Encrypt(String sSrc, String sKey){
        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
            System.out.print("Key长度不是16位");
            return null;
        }
        byte[] encrypted = new byte[0];
        try {
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Base64().encodeToString(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
    }

    // 解密
    public static String Decrypt(String sSrc, String sKey){
        try {
            // 判断Key是否正确
            if (sKey == null) {
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original, "utf-8");
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }
}

论前置处理器 jsr223 的作用

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册