Laravel - 如何解密 cookie 的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47111847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:54:59  来源:igfitidea点击:

Laravel - How decrypt value of cookie

phplaravellaravel-5

提问by J. Defenses

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

您好,我需要解密 cookie 的值。我创建和销毁的代码:

  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.

但是我需要在不加密的情况下获取 cookie 的值。

回答by jedrzej.kurylo

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

在 Web 请求上下文中,cookie 通常由EncryptCookies中间件自动加密和解密。所以最简单的选择就是启用这个中间件(它在 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 EncryptCookiesmiddleware to learn more about what it does internally.

检查EncryptCookies中间件的代码以了解有关其内部功能的更多信息。

回答by user1718159

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 尝试反序列化该值,而您的值未序列化,这就是您收到错误的原因。您需要传递第二个参数,例如:

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