如何加密和解密 php 中的字符串?

How can I encrypt and decrypt a string in php?

根据这个教程https://www.the-art-of-web.com/php/two-way-encryption/我尝试加密和解密一个字符串。

加密效果很好:

  $token = "The quick brown fox jumps over the lazy dog.";

  $cipher_method = 'aes-128-ctr';
  $enc_key = openssl_digest(php_uname(), 'SHA256', TRUE);
  $enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher_method));
  $crypted_token = openssl_encrypt($token, $cipher_method, $enc_key, 0, $enc_iv) . "::" . bin2hex($enc_iv);
  unset($token, $cipher_method, $enc_key, $enc_iv);

  var_dump($crypted_token);

输出为KZ4LurHESC0Y8/Ufy1wsio6aaYXW7m7KVuW8NBKQhE5CnLspz+540p1ClhIZvKNx::254f830c42c937fb7e1e2444c632a8a4

但是当我想再次解密时:

$crypted_token = "KZ4LurHESC0Y8/Ufy1wsio6aaYXW7m7KVuW8NBKQhE5CnLspz+540p1ClhIZvKNx::254f830c42c937fb7e1e2444c632a8a4";

  list($crypted_token, $enc_iv) = explode("::", $crypted_token);;
  $cipher_method = 'aes-128-ctr';
  $enc_key = openssl_digest(php_uname(), 'SHA256', TRUE);
  $token = openssl_decrypt($crypted_token, $cipher_method, $enc_key, 0, hex2bin($enc_iv));
  unset($crypted_token, $cipher_method, $enc_key, $enc_iv);

  var_dump($token);

我得到输出:

"m PHĝ��Jt�nx���l����$�۩!Z��� [b���f�" 

如我所料:

The quick brown fox jumps over the lazy dog.

代码没有错。 php_uname() 已禁用。启用 php_uname() 并重试。

这意味着响应是二进制格式的。尝试使用 hex2bin() 对其进行转换,看看会得到什么。