これは、データの暗号化/復号化に使用するコードです。
// 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}");
通常は正常に動作しますが、時々 (10 分の 1 またはそれ以下) 失敗します。テキストが部分的にのみ暗号化されているよりも失敗した場合:
これは、発生したときのエラー メッセージです。
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。また、phpfidle.org や 3v4l.org などの複数のオンライン PHP パーサーも試しました。
常に適切な長さの文字列が返されるとは限らないようですopenssl_random_pseudo_bytes
が、その理由はわかりません。
サンプルは次のとおりです: https://3v4l.org/RZV8d
ページを更新し続けると、ある時点でエラーが発生します。