一、在eclipse里面编写MD5加密算法
package com.Base64;import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;public class Md5Utils {public static String md5(String sourceStr) {String result = "";try {MessageDigest md = MessageDigest.getInstance("MD5");md.update(sourceStr.getBytes());byte b[] = md.digest();int i;StringBuffer buf = new StringBuffer("");for (int offset = 0; offset < b.length; offset++) {i = b[offset];if (i < 0)i += 256;if (i < 16)buf.append("0");buf.append(Integer.toHexString(i));}result = buf.toString();
// System.out.println("MD5(" + sourceStr + ",32) = " + result);// System.out.println("MD5(" + sourceStr + ",16) = " + buf.toString().substring(8, 24));} catch (NoSuchAlgorithmException e) {
// System.out.println(e);}return result;}public static void main(String[] args) {String md5Str = md5("123456");System.out.println(md5Str);}
}
二、在eclipse里面自己编写HMACSHA256算法
package com.Base64;import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;public class HMACSHA256 {/*** 将加密后的字节数组转换成字符串** @param b 字节数组* @return 字符串*/public static String byteArrayToHexString(byte[] b) {StringBuilder hs = new StringBuilder();String stmp;for (int n = 0; b!=null && n < b.length; n++) {stmp = Integer.toHexString(b[n] & 0XFF);if (stmp.length() == 1)hs.append('0');hs.append(stmp);}return hs.toString().toLowerCase();}/*** sha256_HMAC加密* @param message 消息* @param secret 秘钥* @return 加密后字符串*/public static String sha256_HMAC(String message, String secret) {String hash = "";try {Mac sha256_HMAC = Mac.getInstance("HmacSHA256");SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");sha256_HMAC.init(secret_key);byte[] bytes = sha256_HMAC.doFinal(message.getBytes());hash = byteArrayToHexString(bytes);} catch (Exception e) {System.out.println("Error HmacSHA256 ===========" + e.getMessage());}return hash;}public static void main(String[] args) {String data = sha256_HMAC("123", "abc");System.out.println(data);}}
三、在eclipse里面写好之后,导出来为jar包,命名为:base64.jar 放在jmeter/lib/ext中
1.md5方法就一个参数,就是需要加密的数据
2.sha256_HMAC方法接收两个参数,message:需要被加密的数据,secret:加密的秘钥
四、在jmeter测试计划底部library中添加该jar包,重启jmeter
新建http请求后,在下面加一个前置处理器:BeanShell PreProcessor
直接导入该jar包里面的java包,Md5Utils和HMACSHA256都在在com.Base64这个包里,直接引入,如果导入不了在jmeter的测试计划底部引入即可
插入如下代码:
import com.Base64.*;
//1.测试通过MD5进行加密
String md5Str = Md5Utils.md5("123456");
vars.put("loginPwd",md5Str); //把加密后的内容赋值给到loginPwd变量
log.info(md5Str);
//2.测试通过HMACSHA256进行加密
HMACSHA256 psSha256 = new HMACSHA256();
//调用HMACSHA256类的sha256_HMAC方法,进行hmacsha256加密
//通过abc秘钥对密码123456进行加密
String psStr=psSha256.sha256_HMAC("123456","abc");
log.info(psStr);
五、通过创建前置处理器beanshell脚本进行加密处理
六、对加密后的数据进行引用