Extra string & pipe character in Laravel Cookies

Viewed 259

In a Laravel 6x project I'm working on I'm setting a cookie with:

Cookie::queue('remember_me', json_encode(['uid' => $user->id, 'token' => $token]),2628000);

I'm reading the cookie and decrypting it with:

$cookies = Crypt::decrypt(Cookie::get('remember_me'),false);

This works well, except that the value of $cookies has an extra pre-pended string and a | delimiter in it:

e80cd502fec2a621b624ead8eb1cc91a2e94846b|{"uid":872,"token":"l1214065120208k"}

I can work with that obviously to get what I need but I have been unable to find anything on why that string and | are being prepended to the cookie. Any explanation or documentation link?

I did find another thread here with a similar question but no answer:

How to decrypt cookies in Laravel 8

I also found a thread suggesting that Laravel 8 adds the session_id to the cookie string. Is that what I'm seeing here?

Thanks,

Michael

1 Answers

This value looks to be an HMAC-SHA1 of the cookie name with v2 appended to the end.

This logic is implemented in the CookieValuePrefix class in Laravel and the code looks like so:

public static function create($cookieName, $key)
{
    return hash_hmac('sha1', $cookieName.'v2', $key).'|';
}

This is used in the EncryptCookies middleware when encrypting and decrypting accordingly. The relevant source code is:

// in decrypt() function
$hasValidPrefix = strpos($value, CookieValuePrefix::create($key, $this->encrypter->getKey())) === 0;
$request->cookies->set(
        $key, $hasValidPrefix ? CookieValuePrefix::remove($value) : null
);

// in encrypt() function
$this->encrypter->encrypt(
        CookieValuePrefix::create($cookie->getName(), $this->encrypter->getKey()).$cookie->getValue(),
        static::serialized($cookie->getName())
)

I put this logic into a CyberChef page here to test it out with some local cookies I had and verify the output matches and it did. If you go there and plug in your app key (preferable a disposable one) you should see it output the hash value you have in your question.

Related