PHP openssl_decrypt random_pseudo_bytes 错误,帮帮我

PHP openssl_decrypt random_pseudo_bytes error, help me

我成功地使用 PHP openssl 加密了明文,但是使用 openssl_decrypt,我得到了这个错误。

�RC(�ɸ�gQ���삭

外星语漂浮的原因是什么?我认为这是问题所在:

openssl_random_pseudo_bytes (16). 

openssl_random_pseudo_bytes(opensl_cipher_iv_length ("AES-128-CBC"));也是一样的情况

function aes_encode($text, $s_key){
    $iv = openssl_random_pseudo_bytes(16);
    return base64_encode(openssl_encrypt($text, "AES-128-CBC", $s_key, 0, $iv));
  }

  $encrypt_text = aes_encode($plaintext, $s_key);
  echo $encrypt_text;

function aes_decode($encrypt_text, $s_key){
    $iv = openssl_random_pseudo_bytes(16);
    return openssl_decrypt(base64_decode($encrypt_text), "AES-128-CBC", $s_key, 0, $iv);
}

$decrypt_text = aes_decode($encrypt_text, $s_key);
echo $decrypt_text;

<result>
QUxwTUxiSTkwWFc2WE0zcmtSOXNHR0cyKzU1RWIvNkxnaGJTZmdnVlB4VT0=
�RC(�ɸ�gQ���삭

您需要在解密时使用与加密相同的 IV:

function aes_encode($text, $s_key, $iv){
    return base64_encode(openssl_encrypt($text, "AES-128-CBC", $s_key, 0, $iv));
}

function aes_decode($encrypt_text, $s_key, $iv){
    return openssl_decrypt(base64_decode($encrypt_text), "AES-128-CBC", $s_key, 0, $iv);
}
$plaintext = 'testtest';
$s_key = 'secret';
$iv = openssl_random_pseudo_bytes(16);

$encrypt_text = aes_encode($plaintext, $s_key, $iv);
echo $encrypt_text;

echo "\n";

$decrypt_text = aes_decode($encrypt_text, $s_key, $iv);
echo $decrypt_text;

输出

SVg2Y0FtV1h6RFZac2t5UjhxNDhpdz09
testtest