Rp9*_*Rp9 1 encryption aes laravel
我生成了一个唯一的自定义密钥,需要使用此密钥加密一个值。它的返回错误
唯一支持的密码是具有正确密钥长度的 AES-128-CBC 和 AES-256-CBC。
public function test(){
$key = $this->generateRandomKey();
$newEncrypter = new \Illuminate\Encryption\Encrypter( $key, Config::get('app.cipher') );
echo $encrypted = $newEncrypter->encrypt( 'hello' );
}
protected function generateRandomKey()
{
return 'base64:'.base64_encode(
Encrypter::generateKey(Config::get('app.cipher'))
);
}
Run Code Online (Sandbox Code Playgroud)
小智 7
聚会迟到了,但将其发布在这里,因为有一天可能会对某人有所帮助。如果使用 AES-256-CBC,密钥长度应为 32 个字符;如果使用 AES-128-CBC,密钥长度应为 16 个字符。从vendor\laravel\framework\src\Illuminate\Encryption\Encrypter.php可以看到:
public static function supported($key, $cipher)
{
$length = mb_strlen($key, '8bit');
return ($cipher === 'AES-128-CBC' && $length === 16) ||
($cipher === 'AES-256-CBC' && $length === 32);
}
Run Code Online (Sandbox Code Playgroud)
对于使用自定义密钥加密/解密,您可以使用以下代码片段。
$theOtherKey = "22222222222222222222222222222222"; //32 character long
$text = 'Hello World'; //or the text that you want to encrypt.
$newEncrypter = new \Illuminate\Encryption\Encrypter ($theOtherKey,'AES-256-CBC');
$encrypted = $newEncrypter->encrypt($text);
echo $encrypted;
Run Code Online (Sandbox Code Playgroud)
如果您更喜欢使用 AES-128-CBC,请确保您的 $theOtherKey 的长度为 16 个字符。