Eclipse代码
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class HMAC_data {
public static void main(String[] args) {
//String valMD5 = HMAC_data.encrypt(HMAC_data.datas, HMAC_data.key, HMAC_data.HMAC_MD5);
//String MD5 = "MD5=";
//System.out.println(MD5+valMD5);
String valSha1 = HMAC_data.encrypt(HMAC_data.datas, HMAC_data.key, HMAC_data.HMAC_SHA1);
String SHA1 = "SHA1=";
System.out.println(SHA1+valSha1);
//String valSha256 = HMAC_data.encrypt(HMAC_data.datas, HMAC_data.key, HMAC_data.HMAC_SHA256);
//String SHA256 = "SHA256=";
//System.out.println(SHA256+valSha256);
//String valSha512 = HMAC_data.encrypt(HMAC_data.datas, HMAC_data.key, HMAC_data.HMAC_SHA512);
//String SHA512 = "SHA512=";
//System.out.println(SHA512+valSha512);
}
//加密数据data
public static final String datas = "Jinjie_zdh123Jinjie_zdh123";
//秘钥key
public static final String key = "83ba5ebdbf8a27e6175db676cb1d8652d3499c1c";
//加密方法
public static final String HMAC_SHA1 = "HmacSHA1";
public static final String HMAC_MD5 = "HmacMD5";
public static final String HMAC_SHA256 = "HmacSHA256";
public static final String HMAC_SHA512 = "HmacSHA512";
public static String encrypt(String input, String key, String algorithm) {
String cipher = "";
try {
byte[] data = key.getBytes(StandardCharsets.UTF_8);
//根据给定的字节数组构造一个密钥,第二个参数指定一个密钥的算法名称,生成HmacSHA1专属密钥
SecretKey secretKey = new SecretKeySpec(data, algorithm);
//生成一个指定Mac算法的Mac对象
Mac mac = Mac.getInstance(algorithm);
//用给定密钥初始化Mac对象
mac.init(secretKey);
byte[] text = input.getBytes(StandardCharsets.UTF_8);
byte[] encryptByte = mac.doFinal(text);
cipher = bytesToHexStr(encryptByte);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
e.printStackTrace();
}
return cipher;
}
/**
* byte数组转16进制字符串
*
* @param bytes byte数组
* @return hex字符串
*/
public static String bytesToHexStr(byte[] bytes) {
StringBuilder hexStr = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
hexStr.append(hex);
}
return hexStr.toString();
}
}
BeanShell引用
import HMAC_data.jar;
//加密数据
String datas = "${accountName}${password}";
//秘钥
String key = "${hash}";
//加密方法:"HmacSHA1","HmacMD5","HmacSHA256","HmacSHA512"
String HMAC_SHA1 = "HmacSHA1";
String valSha1 = HMAC_data.encrypt(datas,key,HMAC_SHA1);
//打印
System.out.println(valSha1);
//放入变量login_hash
vars.put("login_hash",valSha1)