首页 > 系统相关 >Jmeter使用beanshell加密,调用AES代码,生成jar包

Jmeter使用beanshell加密,调用AES代码,生成jar包

时间:2022-10-09 19:16:09浏览次数:85  
标签:AES 加密 jar a1 token beanshell import

工作中需要对接口进行AES加密,找开发要来了加密的代码(如下),记录下具体的使用方法:

  1. 新建一个AESUtil包,在里面新建一个类(建议类的名字也为AESUtil)。
  2. 把下面的代码复制进去,注意,导入org.apache.commons.codec.binary.Base64这个包的时候,应该会提示导入错误,这个base64的包可以去网上下载,附上包的链接:https://commons.apache.org/proper/commons-codec/download_codec.cgi
  3. 下载commons-codec-1.15-bin.zip解压,然后使用eclipse导入jar就可以,导入第三方jar的方法在这:https://zhinan.sogou.com/guide/detail/?id=316513460533#
  4. 这样,AES加密的方法就构建好了。接下来就是导出为jar包了。文件-导出-jar-直接下一步就行。
  5. 把生成的jar包,放到jmeter的lib路径下(有的文章说需要放到lib的ext路径下),不过我是放到lib就已经可以使用了。
  6. 需要把jar包的路径,放到测试计划中。

AES加密代码

package AESUtil;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Key;

import org.apache.commons.codec.binary.Base64;//这个base64的包需要从网上下载导入
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Test04 {

    private static final String ALGORITHM = "AES/CBC/PKCS5PADDING";//加密模式:
    private static final String IV_SPEC = "ZAbcd1]YE521at!2";//IV:偏移量,大家根据自己项目上的值,自行更改。
	public static String encrypt(String content, String token) {
        //对content加密,token为加密的秘钥,长度需要为16位
        byte[] result = encryptByte(content.getBytes(StandardCharsets.UTF_8), token.substring(0, 16).getBytes(StandardCharsets.UTF_8));
        return Base64.encodeBase64URLSafeString(result);//对加密后的字符,进行base64转码,不需要的注释掉这行就可以
    }

    static byte[] encryptByte(byte[] content, byte[] token) {
        if (content == null || token == null) {
            return null;
        }
        try {
            Cipher cipher = initCipher(Cipher.ENCRYPT_MODE, token);
            return cipher.doFinal(content);
        } catch (Exception e) {
           // log.error("AES encrypt failed", e);
        }
        return null;
    }

    private static Cipher initCipher(int mode, byte[] token) throws Exception {
        if (token == null) {
            return null;
        }
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        Key key = new SecretKeySpec(token, "AES");
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(IV_SPEC.getBytes(StandardCharsets.UTF_8)));
        cipher.init(mode, key, params);
        return cipher;
    }

}


beanshell中的脚本

import AESUtil.*;//导入AESUtil包
 
String a1 = AESUtil.encrypt("1234","10b457959d4a7a30");	//1234是需要加密的字符,10b457959d4a7a30是加密的秘钥,长度需要为16位	
vars.put("a1",a1);//把a1的内容,赋值给jmeter的变量a1

log.info("a1是"+a1);//打印,显示为加密后的内容

ps:jmeter有可能会报错:版本不兼容,这个问题就去eclipse中,更改编辑器的java版本就好了。

文章部分内容所借鉴的部分:https://blog.csdn.net/qq_25375659/article/details/80944646?spm=1001.2014.3001.5502

标签:AES,加密,jar,a1,token,beanshell,import
From: https://www.cnblogs.com/jike9527/p/16773288.html

相关文章