Home >Backend Development >PHP Tutorial >How to encrypt/decrypt mcrypt?_PHP tutorial
PHP code:------------------------------------------------ ----------------------------------
function make_seed() {
list($usec, $ sec) = explode(' ', microtime());
return(float) $sec +((float) $usec * 100000);
}
srand(make_seed());
/* Turn on the encryption algorithm/ */
$td = mcrypt_module_open('twofish', ', 'ecb', ');
/* Create IV and detect the length of the key*/
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
$ks = mcrypt_enc_get_key_size($td);
/* Generate key */
$key = substr(md5('very secret key'), 0 , $ks);
/* Initialize the encryption program*/
mcrypt_generic_init($td, $key, $iv);
/* Encryption, $encrypted saves the encrypted data*/
print $encrypted = mcrypt_generic($td, 'This is very important data');
/* Detect encryption handle*/
mcrypt_generic_deinit($td);
/* Initialize encryption module for Decrypt*/
mcrypt_generic_init($td, $key, $iv);
/* Decrypt*/
$decrypted = mdecrypt_generic($td, $encrypted);
/* Detect decryption handle, And close the module*/
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
/* Display the original string*/
echo trim($decrypted)."
";