This post is part of our ongoing Encryption Series that provides in-depth coverage of OpenSSL. To learn more about encryption key generation, management, and use please see the posts in the Encryption category. Our tips and tricks are immediately applicable with examples that you can use right away. If you like this article, you may be interested in the Raspberry Pi crypto key management project as well as Rietta’s Application Security Learning Center, our catalog of video resources on how to succeed with web application security.
Web application security is built upon a series of interconnected building blocks.
Last year, I wrote about how Generating an RSA Key from the Command Line in OpenSSL could support encrypting or validating data in an unattended manner (where the password is not required to encrypt). A few weeks before that, I posted about how to Encrypt a File with a Password from the Command Line using OpenSSL.
Knowing how to generate an encryption key is great, but knowing how to use it in your application is even better.
So here is an example PHP function that can encrypt arbitrary data, including strings and arrays, using an RSA public key generated with the example in the previous article.
The Code to Encrypt and Serialize
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
The Output from this Code
On my system, running this script returns a serialized array as a single line of text. In this example, newlines and tabs have been added for readability.
1 2 3 4 5 6 7 8 9
A good encryption scheme will generate different cipher text each time it is run. Therefore, running the script multiple times will result in different looking random data in the encdata and enckeys fields as a different random session key for each run.
Or, If You Want to Use JSON
The serialize function is a specific format to PHP. If you want to use JSON instead, you can do so with something like this at the end of the encryptData function.
1 2 3 4 5 6 7 8 9 10 11 12 13
OpenSSL is a cryptographic foundation upon which you can build some very powerful, flexible, and will help improve the security of your web applications.
Invitation to the Web Application Topics Newsletter
This post is part of the Web Application Topics series. If you are interested in having future issues sent directly to you by e-mail, please sign up for free, today. For back issues, see the Web Application Topics category on this blog.