Wordpress Tutorials

How To Create a Two-Way Encrypt / Decrypt Function In WordPress

You have no doubt heard it a million times before, but the point remains the same, WordPress is so much more than just a simple blogging mechanism, in fact, I would argue you can build any kind of online platform or website with WordPress as its core, you are really only limited by your imagination.

If I am ever starting a project which may require user accounts or lots of database handling requirements, my mind always jumps straight to WordPress. Yes, there are those of you who will argue that all of that can be achieved using specific libraries, but, can you really get all of that set up and working in a matter of minutes? Not easily!

For me, the real benefits of WordPress come with the vast amount of functions made readily available without any additional programming, for example checking whether a user is logged in requires only is_user_logged_in() or the ability to easily send an email with wp_mail().

As you begin building your own custom projects you will begin to rely on these code offerings more and more, but, there will also be occasions where the functionality you need is not readily available, and you are instead required to get your hands dirty with a bit of coding!


WordPress Does Not Always Have Everything You Need

This takes me nicely onto the topic of this article. I was recently working on a project where I needed a data encryption facility to easily encrypt and decrypt a string on multiple occasions around my website, and whilst I stumbled across a few basic options online, I ended up building one of my own which I will share with you here.


Creating A Two-Way Encryption Function

We will build the function up in small blocks in an attempt to help you better understand the inner workings, and aid your learning. I am going to presume that you understand the PHP basics of elements such as variables and functions etc. If you are fairly new to PHP I would fully recommend you check out the book ‘PHP: A Step By Step Guide from Beginner to Export’ by Alexander Clyde.


Step 1.) Creating an Empty Function

<?php
function wpcodetips_twoway_encrypt(){
     // Code to go here
}
?>

The above code will go into the functions.php file within your WordPress installation. Nothing to shout about here, just the bare bones of a PHP function.


Step 2.) Preparing Arguments

The end goal of our function is to be able to pass it a String and have it return either an encrypted or decrypted version of that String back.

So for our two arguments lets feed in a String and a letter to represent which direction of encryption is required.

<?php
function wpcodetips_twoway_encrypt($stringToHandle = '',$encryptDecrypt = 'e'){
     // Code to go here
}
?>

Hopefully, you are still with me, our first argument will be the String we want modifying, and the second argument will either be an ‘e’ or ‘d’ depending on whether we are encrypting or decrypting.

You will also notice I have added some default values to the arguements, these are by no means essential, but they could help reduce the number of errors later on if you forget to provide everything the function requires.


Step 3.) Preparing Encryption Keys

Things are going to ramp up pretty quickly here shortly, scrambling a string can be done in a number of different ways and we are going to use a number of them together to enhance the security.

First things first, you need to understand that the process of being able to modify a String and then revert it back later will require at least one ‘point of reference‘, in our case we will use some ‘encryption key’ strings.

<?php
function wpcodetips_twoway_encrypt($stringToHandle = '',$encryptDecrypt = 'e'){
     // Set secret keys
     $secret_key = 'jf8gf8g^3*s'; // Change this!
     $secret_iv = 'd&&9"dh4%:@'; // Change this!
}
?>

These two strings of $secret_key and $secret_iv (initialization vector) can be whatever you like, but keep in mind that altering them will change the way the entire final function will work.

In other words, if you encrypt a string and then modify the above keys afterward, you will then not be able to decrypt it back again.


Step 4.) Hashing and Encoding

Remember I said that this tutorial was going to ramp up? Well, this is the point where that happens.

In this section, we are going to be using a number of complicated PHP functions, and unless you want to skip to the end and copy the finished code block, I recommend you have a short read of each to understand what they do. Here are the functions we will be integrating:

For both the encrypt and decrypt handlers we will need a singular key. We now have a standard key in our $secret_key so let’s give that a SHA256 Hash and store it in a variable ready to go.

<?php
function wpcodetips_twoway_encrypt($stringToHandle = "",$encryptDecrypt = 'e'){
     // Set secret keys
     $secret_key = 'jf8gf8g^3*s'; // Change this!
     $secret_iv = 'd&&9"dh4%:@'; // Change this!
     $key = hash('sha256',$secret_key);
}
?>

As well as a singular key, both upcoming handlers for the encryption process will require an init vector value and you can read more about those using the function links above. All you really need to know here is that we need a value that is 16 characters in length.

Let’s bust out the ever-handy SHA256 Hash function again and nest that within a substring function to only return the first 16 characters.

<?php
function wpcodetips_twoway_encrypt($stringToHandle = "",$encryptDecrypt = 'e'){
     // Set secret keys
     $secret_key = 'jf8gf8g^3*s'; // Change this!
     $secret_iv = 'd&&9"dh4%:@'; // Change this!
     $key = hash('sha256',$secret_key);
     $iv = substr(hash('sha256',$secret_iv),0,16);
}
?>

We now have everything needed and hopefully, you are still with me! Now we can add the final few lines. First, we will add a simple if statement checking whether we are encrypting or decrypting.

<?php
function wpcodetips_twoway_encrypt($stringToHandle = "",$encryptDecrypt = 'e'){
     // Set secret keys
     $secret_key = 'jf8gf8g^3*s'; // Change this!
     $secret_iv = 'd&&9"dh4%:@'; // Change this!
     $key = hash('sha256',$secret_key);
     $iv = substr(hash('sha256',$secret_iv),0,16);
     // Check whether encryption or decryption
     if($encryptDecrypt == 'e'){
        // We are encrypting
     }else if($encryptDecrypt == 'd'){
        // We are decrypting
     }
}
?>

Now we can add in a nested combination of those complex PHP functions we referenced earlier to handle the ‘scrambling’.

<?php
function wpcodetips_twoway_encrypt($stringToHandle = "",$encryptDecrypt = 'e'){
     // Set secret keys
     $secret_key = 'jf8gf8g^3*s'; // Change this!
     $secret_iv = 'd&&9"dh4%:@'; // Change this!
     $key = hash('sha256',$secret_key);
     $iv = substr(hash('sha256',$secret_iv),0,16);
     // Check whether encryption or decryption
     if($encryptDecrypt == 'e'){
        // We are encrypting
        $output = base64_encode(openssl_encrypt($stringToHandle,"AES-256-CBC",$key,0,$iv));
     }else if($encryptDecrypt == 'd'){
        // We are decrypting
        $output = openssl_decrypt(base64_decode($stringToHandle),"AES-256-CBC",$key,0,$iv);
     }
}
?>

I am not going to explain exactly what is happening here, all I will say is if you really want to full understand what is happening, read up on the functions from the inside out.

The final result is an $output variable that holds what we need. Now we can finish off our function with a default value for that variable, to begin with, and then end by returning it.


The Final Function

<?php
function wpcodetips_twoway_encrypt($stringToHandle = "",$encryptDecrypt = 'e'){
     // Set default output value
     $output = null;
     // Set secret keys
     $secret_key = 'jf8gf8g^3*s'; // Change this!
     $secret_iv = 'd&&9"dh4%:@'; // Change this!
     $key = hash('sha256',$secret_key);
     $iv = substr(hash('sha256',$secret_iv),0,16);
     // Check whether encryption or decryption
     if($encryptDecrypt == 'e'){
        // We are encrypting
        $output = base64_encode(openssl_encrypt($stringToHandle,"AES-256-CBC",$key,0,$iv));
     }else if($encryptDecrypt == 'd'){
        // We are decrypting
        $output = openssl_decrypt(base64_decode($stringToHandle),"AES-256-CBC",$key,0,$iv);
     }
     // Return the final value
     return $output;
}
?>

Step 5.) Taking It For a Spin!

After all of the fun of putting this function together, now is the time to test out our encrypt method and see if it works!

Let’s start by taking a super-secret password and encrypting it. We have one very function now to handle this!

<?php
$originalPassword = 'secretpassword123';
$encryptedPassword = wpcodetips_twoway_encrypt($originalPassword,'e');
echo $encryptedPassword;
?>

This will display the following on-screen:

U3pnaHlydW10ZXVSaWZXM2l3dnRPNUF0dGVCcjV2d1JodXJHQW5rQ05mbz0=

Congratulations you created your first encrypted value! This can now be stored in a database for future use, or however else you intend to use it!

Now let’s use the other side of what we have created. Fingers crossed we can now pass the above-encrypted value back into our same function with a ‘d’ value for the second argument to retrieve the initial value.

<?php
$encryptedPassword = 'U3pnaHlydW10ZXVSaWZXM2l3dnRPNUF0dGVCcjV2d1JodXJHQW5rQ05mbz0=';
$decryptedPassword = wpcodetips_twoway_encrypt($encryptedPassword,'d');
echo $decryptedPassword;
?>

And as if by magic our screens are graced with:

secretpassword123

Congratulations you have successfully created a tool to help your encode and decode strings in any way you please across your project!


Conclusion

I hope you have found this tutorial useful! You now have a handy function to use within your web projects to keep your data safe and sound.

Let us know in the comments below how you plan to make use of it or if you have any questions!


Buy Me a Coffee?Buy Me a Coffee?
Gary

Hi, my name is Gary, I hope to share some of my real-world programming experiences and code solutions to help you develop your Wordpress and WooCommerce skills.

Leave a Reply

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