Simple Two Way Encryption in PHP

In this tutorial, we will see how to encrypt and decrypt a string in PHP. We always use encryption in programming to secure data from malicious user, but this encryption is one way encryption.

In this article we will learn how to use simple two way encryption in PHP.  Here we will use openssl_encrypt() function with salt (secret key).

Let us see the example

<?php
// Encrypt Function
function encrypt($plainText, $key) {
        $secretKey = md5($key);
        $iv = substr( hash( 'sha256', "aaaabbbbcccccddddeweee" ), 0, 16 );
        $encryptedText = openssl_encrypt($plainText, 'AES-128-CBC', $secretKey, OPENSSL_RAW_DATA, $iv);
        return base64_encode($encryptedText);
    }

    //Decrypt Function
  function decrypt($encryptedText, $key) {
        $key = md5($key);
        $iv = substr( hash( 'sha256', "aaaabbbbcccccddddeweee" ), 0, 16 );
        $decryptedText = openssl_decrypt(base64_decode($encryptedText), 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
        return $decryptedText;
    }

// Encrypt data using this function
echo encrypt("Vikash Kumar Singh","MYKEY"); 

// Decrypt data using this function                            
echo decrypt("sFhoDYtPj1samXYten1VcrwLdv3uzQt7VDvjTBJgZkQ=","MYKEY");  
?> 

Want to learn how to make AJAX calls secure. Here is an amazing guide for you.

5 Tips to Secure AJAX PHP Call

1 thought on “Simple Two Way Encryption in PHP”

  1. Great thanks for the tutor. Is there any way i can shorten the length of the encrypted string and remove the special characters like ‘+’ and ‘/’ and simply make it alpha numeric character

    Reply

Leave a Comment