JavaScript PHP Laravel Cryptojs – How to decrypt data encrypted using Crypto-JS in Laravel [closed]

cryptojsjavascriptlaravelphp

I have this bit of code in my js :

export const encrypt = (data, key) => {
    const encrypted = CryptoJS.AES.encrypt(
        JSON.stringify(data),
        key
    ).toString();
    return encrypted;
};

but when i decrypt it in my laravel backend :

Route::post('/decrypt', function (Request $request) {
    try{
        $encrypted = $request->input("data");
        Crypt::decrypt($encrypted);
    }
    catch(DecryptException $e) {
        dd("error", $e);
    }
});

this gives me the DecryptException "The payload is invalid"

Best Answer

This is the function that worked for me with the Crypt::decrypt function in laravel you just have to turn off unserialization

export function encrypt(data, key) {
    let iv = CryptoJS.lib.WordArray.random(16),
        generatedKey = CryptoJS.enc.Base64.parse(key);
    let options = {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
    };
    let encrypted = CryptoJS.AES.encrypt(
        JSON.stringify(data),
        generatedKey,
        options
    );
    encrypted = encrypted.toString();
    iv = CryptoJS.enc.Base64.stringify(iv);
    let result = {
        iv: iv,
        value: encrypted,
        mac: CryptoJS.HmacSHA256(iv + encrypted, generatedKey).toString(),
    };
    result = JSON.stringify(result);
    result = CryptoJS.enc.Utf8.parse(result);
    result = CryptoJS.enc.Base64.stringify(result);
    return result;
}
private function decryptValue($value)
    {
        try {
            return json_decode(Crypt::decrypt($value, false), true);
        } catch (\Exception $e) {
            throw new DecryptException('Decryption failed: ' . $e->getMessage());
        }
    }