前端数据加密解密
使用crypto-js
加解密代码如下
encryptECB(word, EK) {
if (word === null) {
return word;
}
let key = CryptoJS.enc.Utf8.parse(EK);
let srcs = CryptoJS.enc.Utf8.parse(word);
let encrypted = CryptoJS.AES.encrypt(srcs, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.ciphertext.toString().toUpperCase();
},
/** ECB解密 */
decryptECB(word, EK) {
if (word === null) {
return word;
}
let key = CryptoJS.enc.Utf8.parse(EK);
let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
let decrypt = CryptoJS.AES.decrypt(srcs, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
return decryptedStr.toString();
},
/** CBC加密 */
encryptCBC(word, EK) {
if (word === null) {
return word;
}
let iv = CryptoJS.enc.Utf8.parse(EK);
let key = CryptoJS.enc.Utf8.parse(EK);
let srcs = CryptoJS.enc.Utf8.parse(word);
let encrypted = CryptoJS.AES.encrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
});
return encrypted.toString();
},
/** CBC解密 */
decryptCBC(word, EK) {
if (word === null) {
return word;
}
let iv = CryptoJS.enc.Utf8.parse(EK);
let key = CryptoJS.enc.Utf8.parse(EK);
let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
let decrypt = CryptoJS.AES.decrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
});
let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
return decryptedStr.toString();
}
希望可以帮助到你,有用的话记得点赞