这是我用来加密/解密数据的代码:
// Set the method
$method = 'AES-128-CBC';
// Set the encryption key
$encryption_key = 'myencryptionkey';
// Generet a random initialisation vector
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
// Define the date to be encrypted
$data = "Encrypt me, please!";
var_dump("Before encryption: $data");
// Encrypt the data
$encrypted = openssl_encrypt($data, $method, $encryption_key, 0, $iv);
var_dump("Encrypted: ${encrypted}");
// Append the vector at the end of the encrypted string
$encrypted = $encrypted . ':' . $iv;
// Explode the string using the `:` separator.
$parts = explode(':', $encrypted);
// Decrypt the data
$decrypted = openssl_decrypt($parts[0], $method, $encryption_key, 0, $parts[1]);
var_dump("Decrypted: ${decrypted}");
它通常工作得很好,但有时(十分之一甚至更少)它会失败。当它失败时,文本仅被部分加密:
这是发生时的错误消息:
Warning: openssl_decrypt(): IV passed is only 10 bytes long, cipher expects an IV of precisely 16 bytes, padding with \0
当它发生时,加密文本看起来像:
Encrypt me���L�se!
我认为这可能是由 PHP 中的错误引起的,但我已经在不同的主机上进行了测试:PHP 7.0.6 和 PHP 5.6。我还尝试了多个在线 PHP 解析器,例如 phpfidle.org 或 3v4l.org。
似乎openssl_random_pseudo_bytes
并不总是返回适当长度的字符串,但我不知道为什么。
继续刷新页面,您会在某个时候收到错误消息。