How to decrypt cookies in Laravel 8

Viewed 1773

Recently, we upgraded our Laravel application from 5.6 to Laravel 8.18.1. We use cookie decryption in the RouteServiceProvider.php.

HomeController.php

Cookie::queue("channel", "mobile", 60241); // channel encrypted value = eyJpdiI6IjJVTGFzZHdEOXpjMk9VTGFFYmlSbXc9PSIsInZhbHVlIjoid0djMW9zbThWOXFQTk5aVXBDNmJBdz09IiwibWFjIjoiZGM4M2U1YTY0ZjVkNTE4NjBlNzg4NTZiNzhkNjdjYzcyODUzZWU1ZWMzNjdkNGNlMTgyZGIwNmQ4NjYzOWM3MSJ9

In Laravel 5.6, it decrypted the hash as a value directly.

RouteServiceProvider.php

$encrypter = app(\Illuminate\Contracts\Encryption\Encrypter::class);
$channel_cookie = $encrypter->decrypt(Cookie::get('channel')); // result "mobile"

In Laravel 8.18.1, it decrypted the hash as a value with a vertical bar.

RouteServiceProvider.php

$encrypter = app(\Illuminate\Contracts\Encryption\Encrypter::class);
$channel_cookie = $encrypter->decrypt(Cookie::get('channel')); // result "a86aa854d5e61e2873acd30373b6725e36fba671|mobile"
$channel_cookie = explode("|",$channel_cookie)[1]; // result mobile

Is this a safe solution to decrypt cookies in Laravel 8?

1 Answers

You could found the reason of your issue in this security bulletin about prefixing cookies in laravel.

https://blog.laravel.com/laravel-cookie-security-releases

The code were laravel do this operation is in framework source file linked below

https://github.com/laravel/framework/blob/8.x/src/Illuminate/Cookie/CookieValuePrefix.php

In our scenario we have realized something similar the original code, in two words: the cookie name is encrypted and added to cookie value with a | as separation char.

Related