安装
npm install crypto-js --save
npm install jsencrypt --save
核心代码
import { JSEncrypt } from 'jsencrypt'
import CryptoJS from 'crypto-js'
class Decipherer {
constructor() {
// rsa
this.jsEncrypt = new JSEncrypt()
// aes
this.key = '' // 十六位十六进制数作为密钥
this.iv = '' // 十六位十六进制数作为密钥偏移量
}
// rsa 加密
encryptedData(publicKey, data) {
this.jsEncrypt.setPublicKey(publicKey)
return this.jsEncrypt.encrypt(JSON.stringfy(data))
}
// rsa 解密
decryptedData(privateKey, data) {
this.jsEncrypt.setPrivateKey(privateKey)
return this.jsEncrypt.decrypt(JSON.stringfy(data)
}
// aes 解密方法
Decrypt(data) {
const encryptedHexStr = CryptoJS.enc.Hex.parse(data.replace(/[\r\n]/g, ''))
const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr)
const decrypt = CryptoJS.AES.decrypt(srcs, this.key, { iv: this.iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 })
const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
return decryptedStr.toString()
}
// aes 加密
Encrypt(data) {
const srcs = CryptoJS.enc.Utf8.parse(data)
const encrypted = CryptoJS.AES.encrypt(srcs, this.key, { iv: this.iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 })
return encrypted.ciphertext.toString().toUpperCase()
}
// aes,密钥key 偏移量设置
setDate(key, iv) {
this.key = CryptoJS.enc.Utf8.parse(key) // 十六位十六进制数作为密钥
this.iv = CryptoJS.enc.Utf8.parse(iv) // 十六位十六进制数作为密钥偏移量
}
}
export default new Decipherer()