Created
December 3, 2019 06:47
-
-
Save huzemin/e8d7a904cec55d4d7635c9322f143c42 to your computer and use it in GitHub Desktop.
laravel Encrypt convert to CryptoJS in Javascript
This file contains 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 LaravelEncrypt = function (key) { | |
this.key = key; | |
} | |
LaravelEncrypt.prototype.decrypt = function (encryptStr) { | |
encryptStr = CryptoJS.enc.Base64.parse(encryptStr); | |
let encryptData = encryptStr.toString(CryptoJS.enc.Utf8); | |
encryptData = JSON.parse(encryptData); | |
let iv = CryptoJS.enc.Base64.parse(encryptData.iv); | |
var decrypted = CryptoJS.AES.decrypt(encryptData.value, CryptoJS.enc.Utf8.parse(this.key), { | |
iv : iv, | |
mode: CryptoJS.mode.CBC, | |
padding: CryptoJS.pad.Pkcs7 | |
}); | |
decrypted = CryptoJS.enc.Utf8.stringify(decrypted); | |
return decrypted; | |
}; | |
LaravelEncrypt.prototype.encrypt = function (data) { | |
let iv = CryptoJS.lib.WordArray.random(16), | |
key = CryptoJS.enc.Utf8.parse(this.key); | |
let options = { | |
iv: iv, | |
mode: CryptoJS.mode.CBC, | |
padding: CryptoJS.pad.Pkcs7 | |
}; | |
let encrypted = CryptoJS.AES.encrypt(data, key, options); | |
encrypted = encrypted.toString(); | |
iv = CryptoJS.enc.Base64.stringify(iv); | |
let result = { | |
iv: iv, | |
value: encrypted, | |
mac: CryptoJS.HmacSHA256(iv + encrypted, key).toString() | |
} | |
result = JSON.stringify(result); | |
result = CryptoJS.enc.Utf8.parse(result); | |
return CryptoJS.enc.Base64.stringify(result); | |
}; | |
export default LaravelEncrypt; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I make some adjustment..
I'm using laravel v8.x and vuejs v3.
Assume both
APP_KEY
in Laravel and Vuejs are match. Do not forget to remove prefixbase64:
in .env vuejsAt laravel code:
Then at vuejs:
You just need to change the key from
CryptoJS.enc.Utf8.parse(this.key)
toCryptoJS.enc.Base64.parse(this.key)
in vuejs.Also set
unserialize
tofalse
atdecrypt
andencrypt
function in Laravel.