フロントエンドAESとRSAの復号化
1578 ワード
インストール
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
]/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()