使用PHP的OpenSSL_encrypt / OpenSSL_decrypt来加密/解密数据

时间:2017-12-10 17:45:59

标签: php hash passwords

尝试使用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==

1 个答案:

答案 0 :(得分:1)

常量不需要变量名称的$后缀。因此,只需从常量中删除$即可 即。

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

应该是

if ($action == OPENSSL_ENCRYPTz) 

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