Home » Simple two-way function to encrypt or decrypt a string
encryption-decryption
PHP

Simple two-way function to encrypt or decrypt a string

This function will provide you a two-way system to encrypt a string or decrypt an encrypted string.

/**
 * Encrypts or decrypts a string using AES-256-CBC encryption with a secret key and initialization vector.
 *
 * @param string $string The string to be encrypted or decrypted.
 * @param string $action The action to perform. 'e' for encryption, 'd' for decryption. Default is 'e'.
 * @return string|false The encrypted or decrypted string, or false on failure.
 */
function my_simple_crypt($string, $action = 'e')
{
    // you may change these values to your own
    $secret_key = 'my_simple_secret_key';
    $secret_iv = 'my_simple_secret_iv';

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

    if ($action == 'e') {
        $output = base64_encode(openssl_encrypt($string, $encrypt_method, $key, 0, $iv));
    } else if ($action == 'd') {
        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
    }

    return $output;
}

So, how to encrypt a string?
Just call this function and pass your string. Additionally set your second parameter to 'e' (optional). To encrypt Hello World!, write-

$encrypted = my_simple_crypt( 'Hello World!', 'e' );

It’ll generate a encrypted string RTlOMytOZStXdjdHbDZtamNDWFpGdz09

And, how to decrypt?
Pass your encrypted string to the function and set second parameter to 'd'.

$decrypted = my_simple_crypt( 'RTlOMytOZStXdjdHbDZtamNDWFpGdz09', 'd' );

1 Comment

Click here to post a comment

87 + = 91

  • This is the perfect site for anybody who would like to understand this topic. You know so much its almost hard to argue with you (not that I actually would want toÖHaHa). You definitely put a fresh spin on a topic that has been discussed for many years. Excellent stuff, just excellent!