Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - Decrypt Crypt::encrypt in Javascript

I'm using Crypt::encrypt to encrypt my data and feed to Javascript code. How can I decrypt the data in Javascript?

like image 290
hungneox Avatar asked Aug 15 '15 13:08

hungneox


People also ask

How do I encrypt data that needs to be decrypted in node JS?

// 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.

Which encrypt mode is used in Laravel?

Laravel's encrypter uses OpenSSL to provide AES-256 and AES-128 encryption.


2 Answers

Using laravel 5.1 and CryptoJS which can be found at (https://code.google.com/p/crypto-js/).

in .env set:

  1. APP_KEY=uberkeythatrocks

in config/app.php set:

  1. 'cipher' => 'AES-256-CBC'

in MyController.php:

  1. $mySecret = "Something I wanna hide from them";

  2. $encrypted = Crypt::encrypt($mySecret);

in index.js:

  1. var key = "uberkeythatrocks";

  2. var decrypted = CryptoJS.AES.decrypt(encrypted, key);

  3. 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

  1. C:/mylaravel> php artisan key:generate [enter]

To use AES-128-CBC

  1. Edit config/app.php and set 'cipher' => 'AES-128-CBC'

then

  1. C:/mylaravel> php artisan key:generate [enter]

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! :)

like image 179
wubsite Avatar answered Nov 14 '22 10:11

wubsite


CryptoJs and Laravel 6 & 7.x

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)); 
like image 4
SirCumz Avatar answered Nov 14 '22 11:11

SirCumz