据我所知,Laravel中的应用程序密钥为会话和敏感数据提供保护,但我想了解它是如何实现的?它的目的是什么?
我找不到任何相关信息。
据我所知,Laravel中的应用程序密钥为会话和敏感数据提供保护,但我想了解它是如何实现的?它的目的是什么?
我找不到任何相关信息。
APP_KEY 用于加密而不是哈希。你在应用程序中加密的每个数据都在幕后使用 APP_KEY。请记住,加密的数据可以被解密,但哈希的数据无法被解密。
APP_KEY 的一个常见误解是它与密码哈希有关,事实并非如此。以下是证明。
你可以看到上面的推文中 APP_KEY 和哈希数据无关。
你的 Laravel 应用程序中使用加密(不是哈希)的每个组件都使用 APP_KEY (会话、CSRF 令牌和 Cookies)。
在 Laravel 中使用哈希的地方,例如密码、password_reset_token等,不会使用 APP_KEY。
因此,更改 APP_KEY 不会对您的密码或 password_reset_token造成任何问题。
APP_KEY 是应用程序中的私有字符串(加密密钥),没有人知道。因此,如果只有应用程序知道该密钥,则只有应用程序才能解密由该密钥加密的数据。这就是其安全性的原理。
** 要了解有关其功能如何运行的更多信息,您可以简单地检查项目中的此文件:EncryptionServiceProvider.php
这里的注释说明它被用于加密器中。我在这里和这里发现它与openssl_encrypt和openssl_decrypt一起使用。如果没有这个密钥,您无法解密使用这两个函数加密的任何内容,例如存储在用户计算机上的会话cookie。如果它们没有加密,任何能够访问它们的人都可以用您的身份登录到应用程序中。
实际上,应用程序密钥在 Laravel 中用于所有加密数据。如果应用程序密钥未在 .env
中配置,则您的所有会话和其他加密数据将不安全!
要了解更多信息,请搜索 Laravel 文档 中的应用程序密钥。
如果您查看Laravel核心,会发现有一个加密器类(命名空间为Illuminate\Encryption),它使用app_key。还有一个方法是
/**
* Encrypt the given value.
*
* @param mixed $value
* @param bool $serialize
* @return string
*
* @throws \Illuminate\Contracts\Encryption\EncryptException
*/
public function encrypt($value, $serialize = true)
{
$iv = random_bytes(openssl_cipher_iv_length($this->cipher));
// First we will encrypt the value using OpenSSL. After this is encrypted we
// will proceed to calculating a MAC for the encrypted value so that this
// value can be verified later as not having been changed by the users.
$value = \openssl_encrypt(
$serialize ? serialize($value) : $value,
$this->cipher, $this->key, 0, $iv
);
if ($value === false) {
throw new EncryptException('Could not encrypt the data.');
}
// Once we get the encrypted value we'll go ahead and base64_encode the input
// vector and create the MAC for the encrypted value so we can then verify
// its authenticity. Then, we'll JSON the data into the "payload" array.
$mac = $this->hash($iv = base64_encode($iv), $value);
$json = json_encode(compact('iv', 'value', 'mac'));
if (json_last_error() !== JSON_ERROR_NONE) {
throw new EncryptException('Could not encrypt the data.');
}
return base64_encode($json);
}
这个方法用于处理会话和Cookie,它在两个地方被使用。以下是方法:
这个是用于会话的。
/**
* Prepare the serialized session data for storage.
*
* @param string $data
* @return string
*/
protected function prepareForStorage($data)
{
return $this->encrypter->encrypt($data);
}
这是关于Cookies的内容
/**
* Encrypt the cookies on an outgoing response.
*
* @param \Symfony\Component\HttpFoundation\Response $response
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function encrypt(Response $response)
{
foreach ($response->headers->getCookies() as $cookie) {
if ($this->isDisabled($cookie->getName())) {
continue;
}
$response->headers->setCookie($this->duplicate(
$cookie, $this->encrypter->encrypt($cookie->getValue(), static::serialized($cookie->getName()))
));
}
return $response;
}
当然,还有其他使用自己加密方法的包,例如位于供应商文件夹中的Swift Mailer。