关于 Laravel 加密的问题

Questions about Laravel encryption

我对 Laravel 的加密 class 有一些疑问。我希望有人能回答他们。

这里主要是关于第 70 行的 encrypt 方法:

https://github.com/illuminate/encryption/blob/master/Encrypter.php#L70

public function encrypt($value)
{
    $iv = random_bytes(16);

    $value = \openssl_encrypt(
        serialize($value), $this->cipher, $this->key, 0, $iv
    );

    if ($value === false) {
        throw new EncryptException('Could not encrypt the data.');
    }

    $mac = $this->hash($iv = base64_encode($iv), $value);

    $json = json_encode(compact('iv', 'value', 'mac'));

    if (! is_string($json)) {
        throw new EncryptException('Could not encrypt the data.');
    }

    return base64_encode($json);
}

我了解了 openssl_encrypt,它似乎很适合个人用例。我已经使用它制作了加密和解密方法。

Laravel 所做的不仅仅是简单的加密。

如果有人能花点时间看一下指定行上的 github 存储库,我将非常高兴。

干杯!

Why does laravel serialize the value on encryption? If it's always a string that this method takes what is the advantages of serializing the data?

该函数不只是一个字符串。它采用任何(可序列化的)数据类型。它序列化输入值以将其转换为字符串;一种可以在解密后 return 变回其原始类型的类型。我知道函数上方的 PhpDoc 指出参数是一个字符串,但这似乎是错误的,需要更改为 mixed.

Why is base64_encode being used here?

base64 编码用于 $iv,通过 hash 方法将随机字节转换为可用的字符串。

至于 base64 编码 return 值,我不知道。似乎他们可以将其保留为 json 编码的字符串,但也许他们想确保 returned 字符串没有任何特殊字符,或者他们可能想要更多混淆。

Why are the values json_encoded? Is this used to keep a clean array or for other intents as well? Currently in my class's encrypt() method I simply concat the encrypted $value and $iv(Initialization vector). On decrypt I break them apart again.

是的,json_encoding 只是为了帮助促进干净且易于解析的有效负载。它们具有三个需要跟踪的值,并且能够保持值分离的最简单和最干净的方法是使用数组。

Won't the openssl_encrypt throw already throw an exception when it can not encrypt data? Why is the return value checked if this is the case?

我在 PHP documentation 中没有看到任何迹象表明 openssl_encrypt 会抛出异常。然而,它确实声明它 returns false 失败,这是对 false.

进行严格检查的原因

现在,它可能发出 PHP 警告的原因有两个,Laravel 会转换为异常,但这并不是加密失败的唯一两种方式。