Search code examples
javascriptlaravelencryptionaescryptojs

Laravel 7.x Encrypt, CryptoJS decrypt?


I am trying to decrypt a string that i created on Laravel 7.x, using the default encryptor 'Crypt::encryptString' , which is suggested by the Laravel documentation, the problem is i searched everywhere for a way to decrypt the message on javascript level, and i always end up with an empty string, I used the following code, but didn't work for me, i tried to read the laravel internal Encryption class.

the way i encrypt messages

$test = Crypt::encryptString('Testing this');

solutions i tried:

1.the following code

https://gist.github.com/huzemin/e8d7a904cec55d4d7635c9322f143c42

2.CryptoJS, i tried multiple different options, nothing worked

One more little thing, when laravel generated a key it always starts with base64:, i am supposed to take that as part of the key right?

Example:

APP_KEY=base64:0q2V8/90FYnWmEKpks13QMPHoEJhZLlEcr9eW0BMdhU=
//This is my key on the .env

$test = Crypt::encryptString('Testing this');
//eyJpdiI6Ilk0TGJ4eEh3WGUyTzhaWVdCMXY4SHc9PSIsInZhbHVlIjoiU3JuQXh0ekl6cEpBekgwVnJKSzBZZz09IiwibWFjIjoiYTRjYTM5ZTJlNzViMjVmZDIxMWU0Y2M0ZmQ4Y2YyZDVkZDMzOGZiMGZmMDU5N2RjNDYxMDcxMDcyNzA4ZjIzNiJ9

Thanks in advance.


Solution

  • Ok so it turned out that the script on the gist, is almost there i just had to change the way i fetch the key as per "tim-reynolds-thegrommet" comment there on line 23, annnnd on line 12 (thats what he didn't mention) maybe it was too obvious i felt dumb :(, anyway so every

    CryptoJS.enc.Utf8.parse(this.key)
    

    should be changed into

    CryptoJS.enc.Base64.parse(this.key)
    

    and yes you dont need the "base64:" in the key from .env laravel file, just copy the rest,

    Ex:

    APP_KEY=base64:0q2V8/90FYnWmEKpks13QMPHoEJhZLlEcr9eW0BMdhU=
    

    just take

    0q2V8/90FYnWmEKpks13QMPHoEJhZLlEcr9eW0BMdhU=
    

    as your key, Thanks to Robert Harvey comment.