I'm using Crypt::encrypt
to encrypt my data and feed to Javascript code. How can I decrypt the data in Javascript?
// crypto module const crypto = require("crypto"); const algorithm = "aes-256-cbc"; // generate 16 bytes of random data const initVector = crypto. randomBytes(16); // protected data const message = "This is a secret message"; // secret key generate 32 bytes of random data const Securitykey = crypto.
Laravel's encrypter uses OpenSSL to provide AES-256 and AES-128 encryption.
Using laravel 5.1 and CryptoJS which can be found at (https://code.google.com/p/crypto-js/).
in .env set:
in config/app.php set:
in MyController.php:
$mySecret = "Something I wanna hide from them";
$encrypted = Crypt::encrypt($mySecret);
in index.js:
var key = "uberkeythatrocks";
var decrypted = CryptoJS.AES.decrypt(encrypted, key);
var readable = decrypted.toString(CryptoJS.enc.Utf8);
IMPORTANT: The 'key' in PHP must be the same with 'key' in JS and the 'cipher' in PHP must be the same in JS however, CryptoJS will automatically select either AES-128-CBC or AES-256-CBC depending on the length of your 'key'. Although laravel 5.1 default 'cipher' is AES-256-CBC so I would suggest you get your 'key' from .env file to use in JS.
To change or generate a new 'key' from Laravel
To use AES-128-CBC
then
NOTE that the change of 'key' will mean that an existing user account login password will not work unless you delete the user and then create new.
HOPE THIS HELPS! :)
Place a Mix variable inside .env file
MIX_APP_KEY=${APP_KEY}
See: https://laravel.com/docs/7.x/mix#environment-variables
In /resources/assets/js/app.js add:
const CryptoJS = require("crypto-js");
window.decrypt = (encrypted) => {
let key = process.env.MIX_APP_KEY.substr(7);
var encrypted_json = JSON.parse(atob(encrypted));
return CryptoJS.AES.decrypt(encrypted_json.value, CryptoJS.enc.Base64.parse(key), {
iv : CryptoJS.enc.Base64.parse(encrypted_json.iv)
}).toString(CryptoJS.enc.Utf8);
};
And finally somewhere in your script you can decrypt like so:
console.log(decrypt(encrypted_text));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With