middleground_code_v2/src/utils/cryptoEncryption.js

75 lines
2.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import CryptoJS from 'crypto-js'
// 实现加密方法
// export function encryp( data ){
// if( typeof data === "object" ){
// // 如果传入的data是json对象先转义为json字符串
// try {
// data = JSON.stringify(data)
// } catch (error) {
// }
// }
// let iv = CryptoJS.enc.Utf8.parse("lucasnetLUCASNET")
// let key = 'ZJya1314Hzya1314'
// // 统一将传入的字符串转成UTF8编码
// const dataHex = CryptoJS.enc.Utf8.parse( data ) // 需要加密的数据
// const keyHex = CryptoJS.enc.Utf8.parse( key ) // 秘钥
// const ivHex = CryptoJS.enc.Utf8.parse( iv ) // 偏移量
// const encrypted = CryptoJS.AES.encrypt( dataHex , keyHex , {
// iv: ivHex,
// mode: CryptoJS.mode.CBC, // 加密模式
// padding: CryptoJS.pad.Pkcs7
// })
// let encryptedVal = encrypted.ciphertext.toString()
// return encryptedVal // 返回加密后的值
// }
export function encryp(word) {
let iv = CryptoJS.enc.Utf8.parse("ZJya1314Hzya1314")
let key = CryptoJS.enc.Utf8.parse("ZJya1314Hzya1314")
let encrypted = "";
if (typeof word == "string") {
let srcs = CryptoJS.enc.Utf8.parse(word);
encrypted = CryptoJS.AES.encrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
} else if (typeof word == "object") {
//对象格式的转成json字符串
let data = JSON.stringify(word);
let srcs = CryptoJS.enc.Utf8.parse(data);
encrypted = CryptoJS.AES.encrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
}
return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
}
// 解密数据
export function decrypt( encryptedVal) {
/*
传入的key和iv需要和加密时候传入的key一致
*/
// 统一将传入的字符串转成UTF8编码
let encryptedHexStr = CryptoJS.enc.Hex.parse(encryptedVal);
let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
const key = CryptoJS.enc.Utf8.parse("ZJya1314Hzya1314") // 秘钥
const iv = CryptoJS.enc.Utf8.parse("ZJya1314Hzya1314") // 偏移量
let decrypt = CryptoJS.AES.decrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
// let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
// return decryptedStr.toString();
return CryptoJS.enc.Base64.stringify(decrypt);
}
// 生成随机字符串
export function randomString() {
// 正好通过encryp方法生成随机字符串
let key = "qwdkshjf9834jsdf";
let iv = "dkfjdfgc987cs6sk";
let word = "skdjhfgc9823kslf"
return encryp(key, iv, word)
}