Learn Codeigniter

How to Encrypt and Decrypt a String In PHP

Here is simple example where we encrypt and decrypt a string in PHP.

Example

<?php
function encrypt_decrypt($action, $string)
{
    $output         = false;
    $encrypt_method = "AES-256-CFB";
    $secret_key     = 'XU*()_%F#D';
    $secret_iv      = 'M23Dyt374';
    $key            = hash('sha512', $secret_key);
    $iv             = substr(hash('sha512', $secret_iv), 0, 16);
    if ($action == 'encrypt') {
        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
    } else if ($action == 'decrypt') {
        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
    }
    return $output;
}
$plain_txt = "This is my plain text";
echo "Plain Text = $plain_txt\n" . "<br>";
$encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
echo "Encrypted Text = $encrypted_txt\n" . "<br>";
$decrypted_txt = encrypt_decrypt('decrypt', $encrypted_txt);
echo "Decrypted Text = $decrypted_txt\n" . "<br>";
?>

Note:Please check openssl encrypt installed and running in your PHP environment.