需求
postman使用AES加密算法赶促,加密請求體焕议,然后修改原始body所森,再發(fā)給后端
實(shí)現(xiàn)
具體使用API是如下圖,collection_request.js
image-20220629135149730.png
有一個update
方法
所以在postman前置腳本中增加如下代碼:
/**
* 加密
*/
function aesEncrypt(data,secret) {
const srcs = CryptoJS.enc.Utf8.parse(data);
// 將密鑰做md散列計算撒蟀,保證密鑰長度
const encrypted = CryptoJS.AES.encrypt(srcs,CryptoJS.MD5(secret), {
iv: [],
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.toString();
}
// 密鑰
const secret = "aXGr7jvD+yq87v9eTIAm0o5LFqAWsPgVmC37fewH";
console.log(`原始body:${pm.request.body.raw}`)
// 加密
let encryptData = aesEncrypt(pm.request.body.raw,secret);
// 修改請求體
pm.request.body.update({mode: 'raw',raw:`{"encrypt":"${encryptData}"}`})
// 修改頭
pm.request.headers.upsert({ key: "Content-Type", value: "application/json"})
console.log(`真實(shí)body:${pm.request.body.raw}`);
效果
image-20220629141108556.png
image-20220629135924794.png
控制臺
image-20220629141237245.png
后端解密工具類
pom需要引入
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.14</version>
</dependency>
該工具類可以解密前端傳來的加密數(shù)據(jù)
//參考引入包
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
public class AesUtils{
public final static String AES_ALGORITHM = "AES/ECB/PKCS5Padding";
public final static String AES = "AES";
public final static String MD5 = "MD5";
public final static String UTF8 = "UTF-8";
/**
* aes ecb 128 加密
* @param content 明文數(shù)據(jù)
* @param secret 密鑰(需要做散列計算)
* @return base64格式的加密字符串
*/
public static String aesEncrypt(String content, String secret) throws RuntimeException{
try {
MessageDigest md = MessageDigest.getInstance(MD5);
// 對密鑰做MD5散列狞膘,保證跨端的密鑰長度一致
SecretKey secretKey = new SecretKeySpec(md.digest(secret.getBytes(UTF8)), AES);
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
// 加密模式
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherBytes = cipher.doFinal(content.getBytes(UTF8));
String result = Base64.encodeBase64String(cipherBytes);
return result;
} catch (Exception e) {
log.error("AES加密異常",e);
throw new RuntimeException("AES加密異常",e);
}
}
/**
* aes ecb 128 解密
* @param content base64格式的加密字符串
* @param secret 密鑰(需要做散列計算)
* @return 明文數(shù)據(jù)
*/
public static String aesDecrypt(String content, String secret) throws RuntimeException{
try {
byte[] dataBytes = Base64.decodeBase64(content);
MessageDigest md = MessageDigest.getInstance(MD5);
// 對密鑰做MD5散列,保證跨端的密鑰長度一致
SecretKey secretKey = new SecretKeySpec(md.digest(secret.getBytes()), AES);
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
// 解密模式
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] plainBytes = cipher.doFinal(dataBytes);
String result = new String(plainBytes, UTF8);
return result;
} catch (Exception e) {
log.error("AES解密異常",e);
throw new RuntimeException("AES解密異常",e);
}
}
}