openssl_decrypt returns 空白

openssl_decrypt returns blank

我尝试了以下代码

  <?PHP
    
       $encrypt_method = "AES-128-CBC";
        $secret_key = 'iuiuiui';
        $secret_iv = '1234567891234567';
        $string="keeri";
    
        // hash
        $key = hash('sha256', $secret_key);
        
        // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
        $iv = substr(hash('sha256', $secret_iv), 0, 16);
         $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
         
          echo "encrypt----)";
          echo $output ;
         
          echo "decrypt---";
           $output1 = openssl_decrypt($string, $encrypt_method, $key, 0, $iv);
           echo $output1;
         
    ?>

并获得以下输出

encrypt----)3BR54C8qvhHG3e4Lgry4uw==decrypt----)

解密字符串($output1)为空。

您的代码运行很好但是您的解密功能的输入数据是错误的。

您正在向 openssl_decrypt 函数提供(原始)明文,而不是 openssl_encrypt[= 加密的数据27=](“输出”)。

关于代码安全性的友好信息:由于您在“CBC”模式下使用 AES 算法,因此有必要使用 随机生成的初始化向量(“iv”) 或您的完整加密变得 易受攻击

这将是您的 encryption/decryption:

的输出
encrypt----)3BR54C8qvhHG3e4Lgry4uw==decrypt---keeri

完整代码:

<?php
$encrypt_method = "AES-128-CBC";
$secret_key = 'iuiuiui';
$secret_iv = '1234567891234567';
$string="keeri";

// hash
$key = hash('sha256', $secret_key);

// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);

echo "encrypt----)";
echo $output ;

echo "decrypt---";
//$output1 = openssl_decrypt($string, $encrypt_method, $key, 0, $iv);
$output1 = openssl_decrypt($output, $encrypt_method, $key, 0, $iv);
echo $output1;
?>