0

I have to decrypt laravel 6 encrypted string with javascript. Key in laravel .env file

APP_KEY=base64:Rva4FZFTACUe94+k+opcvMdTfr9X5OTfzK3KJHIoXyQ=

And in config/app.php file cipher is set to following...

'cipher' => 'AES-256-CBC',

What I have tried so far is given below...

Laravel Code

$test = 'this is test';
$encrypted = Crypt::encrypt($test);

HTML and Javascript Code

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>

var encrypted = 'eyJpdiI6IlB4NG0ra2F6SE9PZmVcL0lpUEFIeVlnPT0iLCJ2YWx1ZSI6IlVMQWJyVjcrcUVWZE1jQ25LbG5NTGRla0ZIOUE2MFNFXC9Ed2pOaWJJaXIwPSIsIm1hYyI6IjVhYmJmZDBkMzAwYzMzYzAzY2UzNzY2';
var key = 'Rva4FZFTACUe94+k+opcvMdTfr9X5OTfzK3KJHIoXyQ='; // this is laravel key in .env file
var decrypted = CryptoJS.AES.decrypt(encrypted, key); 
console.log(decrypted);

Console out put of the above code is given below in screenshot...

enter image description here

I have tried so many other JS pieces of code from google and stack overflow, but no luck.

Update

This is requirement to decrypt string in separate offline system. I am not going to dcrypt with javascript on live website. Rather decryption with java script will be done on offline system.

14
  • Have you tried base64 decoding APP_KEY first?
    – madpoet
    Commented Jul 24, 2020 at 12:12
  • 3
    You should not use laravel APP_KEY in frontend code. NEVER, Laravel uses APP_KEY to encrypt everything inclucing cookies (Session cookie and csrf cookie). Its really bad practice to include your APP_KEY anywhere where user can access it Commented Jul 24, 2020 at 12:16
  • 2
    Why not decrypt it serverside?. Much safer than this. Commented Jul 24, 2020 at 12:21
  • 1
    It really depends on what you are doing, for example chat application. you should be using end to end encryption with diffie helman key exchange. If you are beginner in cryptography and you are working on real project, not some test project, you are in big trouble. its really hard to implement this thing right in the browser. Browsers are not secure environments, especially if you are storing private keys in them. Whats app for eg. uses end to end encryption, but for their browser application they are just forwarding messages to mobile app where keys are securely stored Commented Jul 24, 2020 at 12:35
  • 1
    If you are storing users data in encrypted way, and you want users to access the data in offline mode, you can store data in IndexedDB inside browser, then you can use some key derivation function (Argon2-prefered, PBKDF2) to generate secret (this is how password managers work) and use that generated bytes as your key for encryption and decryption, that way you dont need to store any information about that key, because it can be always generated. Commented Jul 24, 2020 at 12:39

4 Answers 4

9

This is how you decrypt a text in javascript encoded with Laravel using AES-256-CBC as the cipher.

CryptoJS 4.0 is used...

// Created using Crypt::encryptString('Hello world.') on Laravel.
// If Crypt::encrypt is used the value is PHP serialized so you'll 
// need to "unserialize" it in JS at the end.
var encrypted = 'eyJpdiI6ImRIN3QvRGh5UjhQNVM4Q3lnN21JNFE9PSIsInZhbHVlIjoiYlEvNzQzMnpVZ1dTdG9ETTROdnkyUT09IiwibWFjIjoiM2I4YTg5ZmNhOTgyMzgxYjcyNjY4ZGFkNTc4MDdiZTcyOTIyZjRkY2M5MTM5NTBjMmMyZGMyNTNkMzMwYzY3OCJ9';

// The APP_KEY in .env file. Note that it is base64 encoded binary
var key = 'E2nRP0COW2ohd23+iAW4Xzpk3mFFiPuC8/G2PLPiYDg=';

// Laravel creates a JSON to store iv, value and a mac and base64 encodes it.
// So let's base64 decode the string to get them.
encrypted = atob(encrypted);
encrypted = JSON.parse(encrypted);

console.log('Laravel encryption result', encrypted);



// IV is base64 encoded in Laravel, expected as word array in cryptojs
const iv = CryptoJS.enc.Base64.parse(encrypted.iv);

// Value (chipher text) is also base64 encoded in Laravel, same in cryptojs
const value = encrypted.value;


// Key is base64 encoded in Laravel, word array expected in cryptojs
key = CryptoJS.enc.Base64.parse(key);

// Decrypt the value, providing the IV. 
var decrypted = CryptoJS.AES.decrypt(value, key, {
  iv: iv
});

// CryptoJS returns a word array which can be 
// converted to string like this
decrypted = decrypted.toString(CryptoJS.enc.Utf8);

console.log(decrypted); // Voilà! Prints "Hello world!"

4

Like @Dusan Malusev already mentioned:

You should not use Laravel APP_KEY in frontend code. NEVER, Laravel uses APP_KEY to encrypt everything including cookies (Session cookie and csrf cookie).

Your application could be hacked if it's in your html code! To answer your question a bit: use Crypt::decrypt($encrypted) on the server side of your application (within Laravel).

1
  • This is requirement to decrypt string in separate offline system. I am not going to dcrypt with javascript on live website. Rather decryption with java script will be done on offline system. That is why i am doing so
    – shujat132
    Commented Jul 24, 2020 at 12:28
2

Never use your Laravel APP_KEY in frontend. It is a big software vulnerability.

You should create a trait that encrypts and decrypts data before setting and getting data.

To use Laravel Crypt add Encryptable.php

<?PHP
namespace App;

use Illuminate\Support\Facades\Crypt;

trait Encryptable
{
    public function getAttribute($key)
    {
        $value = parent::getAttribute($key);

        if (in_array($key, $this->encryptable)) {
            $value = Crypt::decrypt($value);
        }
        return $value;
    }

    public function setAttribute($key, $value)
    {
        if (in_array($key, $this->encryptable)) {
            $value = Crypt::encrypt($value);
        }

        return parent::setAttribute($key, $value);
    }
}

After that you can use this trait in your models. Add a $encryptable property. Array of columns to be encrypted and decrypted.

class User extends Model
{    
    use Encryptable;
    
    protected $encryptable = [
       'column',
       'anotherColumn',
    ];
}

After that use model as you use before.

0

I have used in ReactJs

CryptoJS 4.1

let key = process.env.REACT_APP_ENCRYTO_KEY

            let encrypted = atob(response.data)
            encrypted = JSON.parse(encrypted)
            const iv = CryptoJS.enc.Base64.parse(encrypted.iv)
            const value = encrypted.value
            key = CryptoJS.enc.Base64.parse(key)
            let decrypted = CryptoJS.AES.decrypt(value, key, {
                iv
            })
            decrypted = decrypted.toString(CryptoJS.enc.Utf8)
            return {
                ...response,
                data: JSON.parse(decrypted)
            }

Laravel 8.x using Encrypter

$encrypter = new Encrypter(Encrypter::generateKey('supported_any_cipher'));
return response($encrypter->encryptString(json_encode($response)), 200);

The supported cipher algorithms and their properties.

['aes-128-cbc' => ['size' => 16, 'aead' => false],
'aes-256-cbc' => ['size' => 32, 'aead' => false],
'aes-128-gcm' => ['size' => 16, 'aead' => true],
'aes-256-gcm' => ['size' => 32, 'aead' => true]]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.