doulian4762 2017-12-10 17:45
浏览 722
已采纳

尝试使用PHP OpenSSL_encrypt / OpenSSL_decrypt加密/解密数据

iam trying to trying to encrypt/decrypt an text using PHP's OpenSSL_encrypt/OpenSSL_decrypt but iam getting some problems on doing it here is what i have tried to do:

my code

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条回答 默认 最新

  • dslfq06464 2017-12-10 19:04
    关注

    Constants do not require the $ suffix that a variable name does. So simply remove the $ from your constants i.e.

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

    should be

    if ($action == OPENSSL_ENCRYPTz) 
    

    This needs amending wherever you use those constants names.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波