现需求,前端传值到后端数据加密,后端返回数据解密
前端需要两个值,rsa私钥 和 des公钥
<script src="https://cdn.bootcdn.net/ajax/libs/jsencrypt/3.3.2/jsencrypt.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jsrsasign/10.8.3/jsrsasign-all-min.js"></script>
<!-- 引用工具包 -->
funHexToStr(str){
//16进制串转字符
let hexArray = str
.replace(/\r|\n/g, "")
.replace(/([\da-fA-F]{2}) ?/g, "0x$1 ")
.replace(/ +$/, "")
.split(" ");
let byteString = String.fromCharCode.apply(null, hexArray);
return window.btoa(byteString);
},
myEncrypt(plaintext,key){
// des加密
key = CryptoJS.enc.Utf8.parse(key)
let encrypted = CryptoJS.TripleDES.encrypt(plaintext, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
});
return encrypted.ciphertext;
},
decode(pwd){
//解密
// 加密后的Base64字符串
const encryptedBase64String = pwd.toString(CryptoJS.enc.Base64);
// 解密 this.key为你的des密钥
const decryptedBytes = CryptoJS.TripleDES.decrypt(encryptedBase64String,
CryptoJS.enc.Utf8.parse(this.key), {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
// 将解密后的字节转换为原始数据
const decryptedJson = decryptedBytes.toString(CryptoJS.enc.Utf8);
// 解析JSON字符串以获取原始数据对象
const decryptedData = JSON.parse(decryptedJson);
console.log('Decrypted Data:', decryptedData);
},
rsaQM(rsaKey,pwd){
// rsa私钥签名
rsaKey = "-----BEGIN PRIVATE KEY-----\n" + rsaKey + "-----END PRIVATE KEY-----\n";
rsaKey = KEYUTIL.getKey(rsaKey);
const signature = new KJUR.crypto.Signature({
alg: 'MD5withRSA'
});
signature.init(rsaKey);
signature.updateString(pwd);
let a = signature.sign();
let sign = hextob64(a);
return sign;
},
axiosFun(){
//传入后端
//此为我需要传入后端的对象
const data = [data.enteringGinseng].map(item => {
const obj = {};
for(let key in item){
obj[key] = item[key].price || null;
}
return obj;
})
console.log(data);
let pwd = this.myEncrypt(JSON.stringify(data),this.key);// des加密
const key = this.funHexToStr(this.rsaKey);// rsa私钥转base64
const sign = this.rsaQM(key,pwd);// rsa私钥签名
pwd = CryptoJS.enc.Base64.stringify(pwd);// des加密转base64
//将需要加密的值的传入给后端
...
//后端返回成功的值调用this.decode('后端返回的值')进行解密
}
最后显示结果