Encryption in PHP | What, Why, When?

We live in an age of data. I mean, come on! The entire internet is just a big chank of data, isn’t it? From your Facebook status to that selfie you took last time, everything is just a form of data. Now that we are dealing with data every single day in our daily life, this doesn’t mean all data should be unprotected and public, right? This is what we’re going to talk about in this article. Like, what is encryption and how encryption in PHP works, why we need it, and when we need it. While encryption itself is a complex topic, I’ll try my best to explain everything in a fun way. So, without further talking, let’s get started!

green and white line illustration
Photo by Markus Spiske on Pexels.com

What is encryption?

As I said before, I’ll try to avoid all the complex words while explaining encryption ;p. Think of a scene where you need to send an email/letter to your friend, and another guy will carry the letter to deliver to your desired person. But the letter contains sensitive information. That’s why you don’t want the carrier to have the information even if he uncovers the letter and reads it. So, you wrote the letter by changing the position of Alphabets by one. That means, instead of writing “good”, you wrote “hppe”. And you told your friend about this fact while the carrier doesn’t know anything about it. Now, if the carrier opens the letter, “hppe” will make zero sense to him, while your friend can easily convert it back to “good” and read easily.

Congrats, you just did something a bit of encryption! Your original text, which is “good” in our example is called plaintext in encryption. And the converted text which is “hppe” in our example is called ciphertext. I hope now you got the point, altering some information to look like some meaningless data is what we call encryption. All encryption follows some algorithm, in our case, which was changing the position of alphabets. Of course, real-world encryption wouldn’t follow such a simple algorithm as we did in this article 😅. Also, real-world encryption takes a key to encrypt something with an algorithm.

Types of encryption

Alright, now we know what exactly encryption is. Now it’s time to learn more about encryption type. Remember we told you about the encryption key in the last section? Well, based on that key, encryption is divided into two types. One is Symmetric Encryption and another one is Asymmetric Encryption. Let’s talk about each one before discussing encryption in PHP 😁

Symmetric Encryption:

Symmetric Encryption

In symmetric encryption, data is encrypted and decrypted with a single encryption key. You should not share the key with anyone who is not supposed to have access to your data. That’s why it’s called a private key. So, if you encrypt your letter using a private key, you must share the private key with your friend as well. Otherwise, he wouldn’t be able to decrypt your letter and read it. You can get an overview of symmetric encryption if you notice the infographic above.

Asymmetric Encryption:

Asymmetric Encryption in PHP

Unlike symmetric encryption, here you don’t have to share your private key with each other in order to transfer encrypted messages. Asymmetric encryption has a whole different story. In asymmetric encryption, your friend shares his public key with you. Which you use to encrypt the letter. But once you have encrypted the letter using the public key, you can no longer decrypt the message using the public key. So, even if the carrier steals your public key, he still can’t decrypt the letter and read it. The only way to decrypt the letter is in your friend’s hand, which is the private key that he hasn’t shared with anyone.

At this point, you should have an idea of how asymmetric encryption works. Yet, let’s recap this one more time. Asymmetric encryption works with two keys. A public key and a private key. Anyone can encrypt data using the public key, but only the private key can decrypt the encrypted data.

Why is encryption necessary?

As we’ve told before, data and information play a great role in our life. We transfer private information over the internet more than ever nowadays. It can be our password, credit card information, social security number, etc. It’s important to protect such sensitive information of us, while they are traveling over the internet. And the best way to do so is by encrypting our data properly.

Besides our personal use case, companies and organization need to pay great attention to data encryption. Because no system is 100% safe from cyber attacks. While we can’t guarantee to prevent cyber attacks, we can at least prevent the damage of cyber attacks by encrypting all the sensitive data we collect, store, and process. This way, even after a company got into any case like data breaches, they can make sure all their user’s credentials are safe by encrypting the credentials properly. It’s a win-win game for both the company or organization and its consumers.

In one line, encryption is necessary to protect data.

When do we need encryption?

We need encryption whenever we’re dealing with sensitive data. For example, while storing sensitive data into the database, or while sending sensitive data to the end-user or to another server. This makes man in the middle attacks useless. Let’s not just talk about servers, we should use encryption in our local devices. Like, our personal desktop or laptop. Our go-to storage is our personal device. Where we store everything from todo notes to banking information. So, when storing information like this on our laptop or desktop, we should use proper encryption as well. This will help you to protect that piece of data while allowing guests to use your device, or if your device ever gets stolen or even lost!

Symmetric encryption in php

Enough talks about encryption altogether 😅, let’s now talk about encryption in PHP. We will begin with symmetric encryption. The function we will use for encryption in PHP is called openssl_encrypt. This function takes 3 mandatory arguments and 5 optional arguments. The first mandatory argument is the data that you want to encrypt, the second one is the algorithm that you want to use in your encryption, and the third one is your encryption key. To see the list of available algorithms available in PHP, use the openssl_get_cipher_methods function.

If you want to learn more about the optional arguments, I will suggest you visit the URL I linked with the function name. Alright, now here’s how to do symmetric encryption in PHP.

<?php
$plaintext = "Your sensitive message";
$cipher = "AES-128-CTR";
$key = "Blog Desire";
$iv = "1232434565432123";
$ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options=0, $iv);
echo $ciphertext;

In the example above, your sensitive message is saved under the $plaintext variable, and the $cipher is the algorithm we’re using in the current encryption. The $key variable holds our encryption key, which is “Blog Desire” in our example. The next one is $iv, which holds the Initial Vector. For decryption, make sure you’ve saved your $key and $iv.

And here’s how to do asymmetric decryption in PHP

<?php
$encrypted_text = "qnHWqq1mElDqW2RCepH14VriPf5s2Q==";
$cipher = "AES-128-CTR";
$key = "Blog Desire";
$iv = "1232434565432123";
$original_text = openssl_decrypt ($encrypted_text, $cipher, $key, $options = 0, $iv);
echo $original_text;

Asymmetric encryption in PHP

As we’ve discussed before, asymmetric encryption takes two keys. One is the public key and another one is the private key. The public encryption key is responsible for doing encryption and the private encryption key is required to decrypt the encrypted text. Now, our first task is to get the two keys. So, we’ll create a private and public key using the openssl_pkey_new function and save it under the $result variable. Eg:

$result = openssl_pkey_new(array("private_key_bits" => 4096));

But it’s still not ready to use. We need to export the private key out of the $result variable. Here’s how to do it.

openssl_pkey_export($result, $privateKey);

The private key is now saved under the $privateKey variable, time to get the public key and save it under the $publicKey

$publicKey = openssl_pkey_get_details($result)['key'];

Now we have both the private key and the public key. We can encrypt and decrypt data using the keys above. Let’s encrypt something using the public key

$plaintext = "Welcome To Blogdesire";
openssl_public_encrypt($plaintext,$encrypted_text,$publicKey);

We have the encrypted version of the plaintext in the $encrypted_text variable now. And we can easily decrypt the encrypted text using the private key if want.

openssl_private_decrypt($encrypted_text, $plaintext, $privateKey);

It’s just that simple! We can put together everything of the asymmetric encryption in PHP and it will look like this.

<?php
//Initiate the keys
$result = openssl_pkey_new(array("private_key_bits" => 4096));
//Export private key to $privateKey
openssl_pkey_export($result, $privateKey);
//Get the public key
$publicKey = openssl_pkey_get_details($result)['key'];
//Prepare your plain text to encrypt
$plaintext = "Welcome To Blogdesire";
//Encrypt and export encrypted value to $encrypted_text
openssl_public_encrypt($plaintext,$encrypted_text,$publicKey);
//Print encrypted text 
echo $encrypted_text;
//Decrypt the encrypted message using the private key
openssl_private_decrypt($encrypted_text, $plaintext, $privateKey);
//Print the decrypted message
echo $plaintext;

Well, that’s for today guys. I hope you really enjoyed the article as I tried to explain everything in the easiest way possible. If you have any confusion, question, or suggestion regarding the article, feel free to post them in the comment section.

Hi! I write ad free content so you can read without any interruption. If you like my content, please consider buying a coffee for me.
Thanks for your support!

Support me on Buy me a coffee! Buy me a coffee!

Khokon M.

Full Stack Web Developer, Content Writer.

Leave a Reply