-
-
Save miguelortizdev/62fe4cfcc89f692b0e338ffd73d822c8 to your computer and use it in GitHub Desktop.
laravel Encrypt convert to CryptoJS in Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import CryptoJS from "crypto-js"; | |
| const DataEncrypt = function () { | |
| this.key = CryptoJS.enc.Base64.parse(process.env.MIX_APP_KEY.substr(7)); | |
| } | |
| DataEncrypt.prototype.encrypt = function (data) { | |
| let iv = CryptoJS.lib.WordArray.random(16); | |
| let encrypted = CryptoJS.AES.encrypt(data, this.key, { | |
| iv: iv, | |
| mode: CryptoJS.mode.CBC, | |
| padding: CryptoJS.pad.Pkcs7 | |
| }).toString(); | |
| iv = CryptoJS.enc.Base64.stringify(iv); | |
| let result = { | |
| iv: iv, | |
| value: encrypted, | |
| mac: CryptoJS.HmacSHA256(iv + encrypted, key).toString() | |
| } | |
| result = CryptoJS.enc.Utf8.parse(JSON.stringify(result)); | |
| return CryptoJS.enc.Base64.stringify(result); | |
| }; | |
| DataEncrypt.prototype.decrypt = function (encryptStr) { | |
| let str = JSON.parse(atob(encryptStr)), | |
| iv = CryptoJS.enc.Base64.parse(str.iv); | |
| return CryptoJS.AES.decrypt(str.value, this.key, { | |
| iv: iv, | |
| mode: CryptoJS.mode.CBC, | |
| padding: CryptoJS.pad.Pkcs7 | |
| }).toString(CryptoJS.enc.Utf8); | |
| }; | |
| export default DataEncrypt; | |
| ################################################################################ | |
| // 使用: | |
| // .env 文件中增加 | |
| MIX_APP_KEY=${APP_KEY} | |
| import DataEncrypt from "dataEncrypt"; | |
| methods:{ | |
| handelDecrypt() { | |
| let dataDecrypt = new DataEncrypt(); | |
| return JSON.parse(dataDecrypt.decrypt(this.data)); | |
| }, | |
| handelEncrypt() { | |
| let dataDecrypt = new DataEncrypt(); | |
| return JSON.parse(dataDecrypt.decrypt(this.data)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment