Site icon Web Niraj

Create Public / Privacy Encryption Keys and Encrypt / Decrypt Data using PHP

In a recent project, I’ve been using public/private key encryption to transmit data from a mobile application to an API, keeping sensitive information secure as a result. As the API is built in PHP, I was necessary to use PHP to decrypt the incoming data so that it could be processed and stored in the database. This tutorial explains how you can create your own keys, and then use them to encrypt or decrypt data using PHP.

In order to use the below code, your PHP installation needs to support OpenSSL, which is compatible with PHP4.2.0+ and PHP5.

It’s also worth noting that only limited length data can be encrypted using this method. As I’m using a 4096 bit key, I would be able to encrypt a maximum of 512 bytes (if you include the OPENSSL_NO_PADDING flag, but this means that it’s does not conform to the PKCS#1 standard). As padding takes up a minimum of 11 bytes, the maximum data you can encrypt (using the default OPENSSL_PKCS1_PADDING flag) will be 501 bytes (or 0.5 KiB).

Creating the Keys

The first step is to create a pair of keys that will encrypt / decrypt the data for you.

See the gist on github.

Encrypting / Decrypting Data

Using the newly created keys, you can then use the openssl_public_encrypt and openssl_private_decrypt functions to encrypt or decrypt some data, respectively. The below example shows a string that is encrypted using the public key, and decrypted using the private one.

See the gist on github.

You can also do the opposite – encrypt data using the private key (using openssl_private_encrypt) and decrypt data using the public one (using openssl_public_decrypt)

Exit mobile version