This is the code I use to encrypt/decrypt the data:
// 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);
// 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, $method, $encryption_key, 0, $parts);
Warning: openssl_decrypt(): IV passed is only 10 bytes long, cipher expects an IV of precisely 16 bytes, padding with \0
When you generate a random IV, you get raw binary. There's a nonzero chance that the binary strings will contain a
\0 character, which you're using to separate the IV from the ciphertext. Doing so makes
explode() give you a shorter string. Demo: https://3v4l.org/3ObfJ
The trivial solution would be to add base64 encoding/decoding to this process.
That said, please don't roll your own crypto. In particular, unauthenticated encryption is dangerous and there are already secure libraries that solve this problem.
Instead of writing your own, consider just using defuse/php-encryption. This is the safe choice.