jmeter AES加密/解密
首先了解一下,什么是AES加密/解密?AES(全称:Advanced Encryption Standard)对称加密算法,也就是加密和解密用到的密钥是相同的,这种加密方式加密速度非常快,
适合经常发送数据的场合,如:数据加密存储、网络通信加密等。
在进行接口测试或接口压测时,有些比较核心的接口有可能会用AES方式对接口的入参或响应内容进行加密/解密。
Jmeter 对AES加密/解密,当前可以通过beanshell 的方式处理。以下是通过网上找了一段AES加密/解密的java代码,根据需要稍微改动一点内容,
看一下怎么在jmeter中将明文进行加密和解密。
完整代码:
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.security.SecureRandom; import java.util.Base64; public class AESUtil { // AES密钥算法 private static final String KEY_ALGORITHM = "AES"; // 加密/解密算法/工作模式/填充方式 private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding"; // 生成密钥 public static String generateAESKey() throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM); keyGenerator.init(128, new SecureRandom()); // 192 and 256 bits may not be available SecretKey secretKey = keyGenerator.generateKey(); return Base64.getEncoder().encodeToString(secretKey.getEncoded()); } // AES加密 public static String encryptAES(String data, String key) throws Exception { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), KEY_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] encrypted = cipher.doFinal(data.getBytes()); return Base64.getEncoder().encodeToString(encrypted); } // 解密 public static String decryptAES(String data, String key) throws Exception { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), KEY_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(data)); return new String(decrypted); } public static void main(String[] args) throws Exception { String key = generateAESKey(); String originalText = "Hello World!"; String encryptedText = encryptAES(originalText, key); System.out.println("Encrypted Text: " + encryptedText); // 解密操作 // String decryptedText = decryptAES(encryptedText, key); // System.out.println("Decrypted Text: " + decryptedText); } } AESUtil aes_obj = new AESUtil(); String key = aes_obj.generateAESKey(); String originalText = "Hello World!"; String value = aes_obj.encryptAES(originalText,key); log.info("密钥key: "+key); log.info("AES加密结果:"+value); //解密 String decryptedText = aes_obj.decryptAES(value, key); log.info("AES解密结果:"+decryptedText); // 将加密结果设置为jmeter参数 vars.put("AES_value",value);
运行结果: