Using PHP “openssl_encrypt” and “openssl_decrypt” to Encrypt and Decrypt Data

Notice: I am not an encryption expert! I didn’t like having my SMTP email password being stored in my database in plain text, so this was my solution. If you are doing something similar, this should be fine. If you are storing SSN or credit card data, you will want to consult with an encryption expert!

The php manual is currently lacking documentation for the “openssl_encrypt” and “openssl_decrypt” functions, so it took me awhile to piece together what I needed to do to get these functions working as a replacement for mcrypt, which has been unmaintained since 2003. Hopefully this will help you get to where you need to go with encrypting and decrypting your data.

First, you will need to generate a pseudo-random string of bytes that you will use as a 256 bit encryption key. The requested length will be 32 (since 32 bytes = 256 bits). If you echo out the key, you will notice that your browser chokes. In order to avoid possible corruption when storing the key in a file or database, we will base64_encode it. Use the code below to generate your key(s). The key will need to be saved since the data has to be encoded and decoded using the same key. If your encrypted data is being stored in a database, your encryption key will most likely need to be stored in a configuration file.

Now that we have our key, we will create the encryption function. We will pass our data to be encoded, and our key, into the function. In addition to our key, there is a secondary random string we will create and use called an initialization vector (IV) that helps to help strengthen the encryption.

Now for the decryption function:

Putting it all together:

The code above will output the following. Note that the encrypted string in the middle will change each time you run the code thanks to our initialization vector:

Hope this helps!

7 thoughts on “Using PHP “openssl_encrypt” and “openssl_decrypt” to Encrypt and Decrypt Data

  1. Very helpful function! Thank you for providing examples that use openssl_random_pseudo_bytes and sha256, as they are more up-to-date for php7 than the deprecated mcrypt method most tutorials seem to use.

Leave a Reply

Your email address will not be published. Required fields are marked *