Simple Two Way Encryption in PHP

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

// 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");  

Leave a Reply

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