Php encrypt decrypt string

In this article, We’ll see how to encrypt a string and decrypt a encrypted string in php?

function encrypt_decrypt($string, $action = 'encrypt') 
        // you may change these values to your own
        $secret_key = 'my_secret_key'; 
        $secret_iv  = 'my_secret_iv';

        $output         = FALSE;
        $encrypt_method = "AES-256-CBC";
        $key            = hash('sha256', $secret_key);
        $iv             = substr(hash('sha256', $secret_iv), 0, 16);

        switch ($action)
             case 'encrypt':
                                $output = base64_encode(openssl_encrypt($string, $encrypt_method, $key, 0, $iv));
             case 'decrypt':
                                $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);

            return $output;

In above, we’ve created a encrypt_decrypt function, it will take two parameters i.e $string and $action

And, how to encrypt?

To generate a encrypted string, simply we need to call encrypt_decrypt function

$encrypt_string = encrypt_decrypt(‘nexladder web tutorials’);

// Output: aVV5ZTc5b0dtUyszbkFEbmNJbzRFcjRZaW1VTm5mc2tRSnJoRlNuZ0lQST0=

And, how to decrypt?

Pass your encrypted string to the function and set second parameter to ‘decrypt’.

$decrypt_string = encrypt_decrypt($encrypt_string, ‘decrypt); // Output: nexladder web tutorials

That’s it!. Please share your thoughts or suggestions in the comments below.

Posted in PHP

Leave a Reply

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