【问题标题】:Tyring to encrypt/decrypt data using PHP's OpenSSL_encrypt/OpenSSL_decrypt尝试使用 PHP OpenSSL_encrypt/OpenSSL_decrypt 加密/解密数据
【发布时间】:2017-12-10 17:45:58
【问题描述】:

我正在尝试尝试使用 PHP 的 OpenSSL_encrypt/OpenSSL_decrypt 加密/解密文本,但我在执行此操作时遇到了一些问题 这是我试图做的:

我的代码

const OPENSSL_ENCRYPTz = 0;
const OPENSSL_DECRYPTz = 1;
function OpenSSLEndeCrypt($action = 0, $string = '') 
{
  $output = false;
  $encrypt_method = "AES-256-CBC";
  //$secret_key = 'This is my secret key';
  // $secret_iv = 'This is my secret iv';
  $key = openssl_random_pseudo_bytes(32);
  //$key = hash('sha256', $secret_key);
  $ivlen = openssl_cipher_iv_length($encrypt_method);
  $iv = openssl_random_pseudo_bytes($ivlen);
  //$iv = substr(hash('sha256', $secret_iv), 0, 16);
  if ($action == $OPENSSL_ENCRYPTz) 
  {
      $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
      $output = base64_encode($output);
  } 
  else if($action == $OPENSSL_DECRYPTz) 
  {
      $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
  }
  return $output;
}
$encrypted_text = OpenSSLEndeCrypt($OPENSSL_ENCRYPTz, 'cs2xCp2F6bk');
echo 'Your Encrypted Text: '. $encrypted_text. '<br />';
echo 'Your Decrypted Text: '. OpenSSLEndeCrypt($OPENSSL_DECRYPTz, $encrypted_text). '<br />';


ERROR/ERRORS/NOTICES (testing in XAMPP PHP 5.6):-
  Notice: Undefined variable: OPENSSL_ENCRYPTz in \tests.php on line 182
  Notice: Undefined variable: OPENSSL_ENCRYPTz in tests.php on line 171
  Your Encrypted Text: NUdXSWFOVms5UHhHMFZrWGp4dE92QT09
  Notice: Undefined variable: OPENSSL_DECRYPTz in tests.php on line 184
  Notice: Undefined variable: OPENSSL_ENCRYPTz in tests.php on line 171
  Your Decrypted Text:  bTVjS2FWeFhkSWVPbG9Xd3BrYnp4ZytWOTdDZmxITXMwZjVsNzZvbExoU25XcEExVmVHaVhZRkt5TE5jTFZ0Mg==

【问题讨论】:

    标签: php hash passwords


    【解决方案1】:

    常量不需要像变量名那样使用$ 后缀。因此,只需从常量中删除 $

    if ($action == $OPENSSL_ENCRYPTz) 
            //     ^ The error
    

    应该是

    if ($action == OPENSSL_ENCRYPTz) 
    

    无论您在哪里使用这些常量名称,都需要修改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-16
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多