J. Defenses
J. Defenses

Reputation: 213

Laravel - How decrypt value of cookie

Hello i need to decrypt value of cookie. My code to create and destroy:

  public function setSession($id){
      Cookie::queue('userId', $id, 10000);
  }

  public function destroySession(){
      Cookie::queue(Cookie::forget('userId'));
  }

But i need to get value of cookie without encrypt.

Upvotes: 6

Views: 27384

Answers (3)

Cesar Devesa
Cesar Devesa

Reputation: 1297

use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Cookie;

 
try {
    $decrypted = Crypt::decryptString(Cookie::get('cookie_name'));
} catch (DecryptException $e) {
    // ...
}

https://laravel.com/docs/10.x/encryption

Upvotes: 2

user1718159
user1718159

Reputation: 581

By default Crypt::decrypt tries to deserialize the value, and yours is not serialized and that's why you get the error. You need to pass a second argument like:

Crypt::decrypt(Cookie::get('userId'), false);

Upvotes: 12

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

In web request context cookies are usually automatically encrypted and decrypted by the EncryptCookies middleware. So easiest option would be just to enable this middleware (and it's enabled by default in Laravel).

If you need to decrypt any value manually, the following will do the trick:

// get the encrypter service
$encrypter = app(\Illuminate\Contracts\Encryption\Encrypter::class);

// decrypt
$decryptedString = $encrypter->decrypt($encryptedString);

Check the code of the EncryptCookies middleware to learn more about what it does internally.

Upvotes: 17

Related Questions