php simple encrypt and decrypt algorithm code example
Example 1: encrypt decrypt php
function encrypt_decrypt($string, $action = 'encrypt')
{
$encrypt_method = "AES-256-CBC";
$secret_key = 'AA74CDCC2BBRT935136HH7B63C27';
$secret_iv = '5fgf5HJ5g27';
$key = hash('sha256', $secret_key);
$iv = substr(hash('sha256', $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;
}
echo "Your Encrypted password is = ". $pwd = encrypt_decrypt('spaceo', 'encrypt');
echo "Your Decrypted password is = ". encrypt_decrypt($pwd, 'decrypt');
Example 2: encrypt/decrypt data php
$key = 'SuperSecretKey';
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, 'I want to encrypt this', MCRYPT_MODE_ECB);
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, MCRYPT_MODE_ECB);