Jmeter、Postman之RSA加密登录接口测试

发布于 2022年 05月 19日 18:29

方法1:直接用在线加密工具进行加密,得到密码

参考地址
输入公钥和密码,直接加密即可
 

方法2:postman工具

步骤1:接口请求获取公钥,在Tests中将公钥设置为环境变量

 

//获取公钥
var data = JSON.parse(responseBody);
var key=data.body;

//设置key
pm.environment.set("key", key);

  

步骤2:使用加密后的密码登录

(1)填写接口参数
密码从环境变量中获取

 (2)Pre-request Script使用上一步的公钥+密码进行加密

脚本如下
//--------------以下为需要加密的内容,可以根据需求定义多个------------------//
var clearText = 'qq123456';   //clearText 对应{{pwd}}的明文,和{{pwd}}的格式要一致
// var clearText = '{"arg1":"def","arg2":123,"arg3":7.89}'; json格式

//获取变量中的公钥
const encrypt_key = pm.variables.get("key");

//const forge_url = 'https://gitee.com/lzq1357/various/raw/master/forge_min.js';
//forge_min.js来自:https://raw.githubusercontent.com/loveiset/RSAForPostman/master/forge.js
//---------------------------------------------------------------------//
//var forge_js =pm.variables.get("forgejs");
//eval("forge_js");

if (!pm.globals.has("forgeJS")) {
    pm.sendRequest("https://gitee.com/lzq1357/various/raw/master/forge_min.js", function (err, res) {
        if (err) {
            console.log(err);
        } else {
            pm.globals.set("forgeJS", res.text());
        }
    })
} else {
    eval(pm.globals.get("forgeJS"));
}

function encryptRsa(encrypt_key, clearText) {
    console.info('cleartext: ' + clearText);
    //注意此处上下的BEGIN PRIVATE KEY不要删除,框架自带的
    const public_key = '-----BEGIN PUBLIC KEY-----\n'
        + encrypt_key
        + '\n-----END PUBLIC KEY-----';
    var publicKey = forge.pki.publicKeyFromPem(public_key);
    var buffer = forge.util.createBuffer(clearText, 'utf8');
    var bytes = buffer.getBytes();
    var encryptedText = forge.util.encode64(publicKey.encrypt(bytes, 'RSAES-PKCS1-V1_5', {
        md: forge.md.sha256.create(),
        mgf1: {
            md: forge.md.sha1.create()
        }
    })
    );
    console.info('encryptedText: ' + encryptedText);
    return encryptedText;
};

//------------------以下内容根据需要修改定义,可以加密多个字段------------------------//
var encryptedText = encryptRsa(encrypt_key, clearText);
postman.setEnvironmentVariable("pwd", encryptedText);     //设置环境变量pwd

  

(3)获取请求结果中的token,设置为环境变量,后续接口可直接使用
//获取token
var data = JSON.parse(responseBody);
var token=data.body.token;
pm.environment.set("token", token);

  

(4)执行请求
 

 方法3:Jmeter

(1)添加获取公钥的接口,挂载json处理器获取公钥
 
(2)添加登录接口,并挂载beanshell预置处理器
添加beanshell预置处理器
 

脚本如下
import org.apache.commons.codec.binary.Base64;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import java.net.URLEncoder;
String RSA_PUB_KEY=vars.get("public_key");//**这里写公钥**
String KEY_ALGORITHM = "RSA";
String SIGNATURE_ALGORITHM = "MD5withRSA";
int MAX_ENCRYPT_BLOCK = 117;
int MAX_DECRYPT_BLOCK = 128;

public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)
            throws Exception {
        byte[] keyBytes = Base64.decodeBase64(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    public static byte[] encryptByPublicKey(byte[] data, String publicKey)
            throws Exception {
        byte[] keyBytes = Base64.decodeBase64(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    String str = vars.get("pwd");//**这里写密码**
String result ="";

try {
    result = Base64.encodeBase64String(encryptByPublicKey(str.getBytes(), RSA_PUB_KEY));
    
    result1 = encryptByPublicKey(str.getBytes(), RSA_PUB_KEY);
    System.out.println(result);
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
    
print(result);
vars.put("sign",result); //最终得到的结果设置为参数sign
return result1;
(3)执行结果
 
参考资料:

推荐文章