Tuesday, December 9, 2008

Php Security - Encryption And Decryption

Encryption And Decryption
These functions allow you to easily encrypt and decrypt text using the mcrypt PHP extension (required) and the Blowfish encryption algorithm.

function Encrypt_Helper($string, $key)
{
if (extension_loaded('mcrypt') === true)
{
return base64_encode(mcrypt_encrypt(MCRYPT_BLOWFISH, substr($key, 0, mcrypt_get_key_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB)), trim($string), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB), MCRYPT_RAND)));
}

return false;
}

function Decrypt_Helper($string, $key)
{
if (extension_loaded('mcrypt') === true)
{
return trim(mcrypt_decrypt(MCRYPT_BLOWFISH, substr($key, 0, mcrypt_get_key_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB)), base64_decode($string), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB), MCRYPT_RAND)));
}

return false;
}
?>



Usage Example

// returns "K9e+8tesCIziQfNH1QFAsQ=="
echo Encrypt_Helper('top secret info', 'this is the password');

// returns "top secret info"
echo Decrypt_Helper('K9e+8tesCIziQfNH1QFAsQ==', 'this is the password');

?>

No comments: