PHP has a lot of available documentation. So much that Googling just about any PHP function provides a php.net result on the first page and a good majority of the content is accurate. And when it’s not, the public comments usually fill in the holes. The OpenSSL cryptography extension is one part of php.net that is very lacking, so much that you’ll even be greeted with Warning: this function is currently not documented; only its argument list is available for both
openssl_decrypt — perhaps the two most commonly looked up OpenSSL functions.
Here’s the full example. We’ll jump into the details below.
Update — 4/3/2017 — Thanks to those commenters who pointed out the issue with the initialization vector clashing. The gist has been updated to base64 encode $iv to mitigate.
This example regenerates the encryption key each time it runs. This is most likely not what you want. Ideally, the encryption key or password should be kept somewhere safe and only readable by the process that’s responsible for encrypting/decrypting.
defineing our cipher, we generate the encryption key / password using
openssl_random_pseudo_bytes. Here we’re creating a 32-byte or 256-bit key (the largest supported by AES).
Next, we create an initialization vector required by the
openssl_encrypt function (well, technically it’s not required but you should use it). We use the same
openssl_random_pseudo_bytes function used to generate the key, but this time we provide it with
openssl_cipher_iv_length to generate the appropriately sized initialization vector for our cipher.
After creating some data to encrypt we use
openssl_encrypt to create our ciphertext. If an initialization vector was used, we must be able to access it again for decryption so the simplest way to do this is to append it to our ciphertext with a separator. Because the initialization vector is not confidential, there’s no need to further encrypt it.
The decryption process starts by splitting the ciphertext into the original ciphertext and the initialization vector. We can then call
openssl_decrypt, providing the original ciphertext, cipher, encryption key, and the initialization vector. The resulting value should match our unencrypted with which we started.
Sign up for Turret.IO — the only data-driven marketing platform made specifically for developers.