【问题标题】:Extra string & pipe character in Laravel CookiesLaravel Cookies 中的额外字符串和管道字符
【发布时间】:2021-07-01 10:09:44
【问题描述】:

在我正在处理的 Laravel 6x 项目中,我正在设置一个 cookie:

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

我正在读取 cookie 并使用以下命令对其进行解密:

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

这很好用,只是 $cookies 的值有一个额外的前置字符串和一个 |分隔符:

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

我显然可以使用它来获得我需要的东西,但我一直找不到任何关于为什么该字符串和 |被添加到 cookie 中。任何解释或文档链接?

我确实在这里找到了另一个有类似问题但没有答案的帖子:

How to decrypt cookies in Laravel 8

我还发现一个线程建议 Laravel 8 将 session_id 添加到 cookie 字符串中。这就是我在这里看到的吗?

谢谢,

迈克尔

【问题讨论】:

    标签: cookies laravel-6


    【解决方案1】:

    此值看起来是 cookie 名称的 HMAC-SHA1,末尾附加了 v2

    这个逻辑在 Laravel 的 CookieValuePrefix 类中实现,代码如下:

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

    这用于EncryptCookies middleware 进行相应的加密和解密。相关源码为:

    // 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())
    )
    

    我将此逻辑放入CyberChef page here 中,以使用我拥有的一些本地cookie 对其进行测试,并验证输出是否匹配。如果您去那里并插入您的应用程序密钥(最好是一次性的),您应该会看到它输出您在问题中的哈希值。

    【讨论】:

      猜你喜欢
      • 2015-01-02
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 2012-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多