Easy Encryption and Decryption using PHP
Special Help from NicholasSolutions
PHP programmers frequently need to temporarily encode data and decode it later. The functions below, which are essentially just wrappers for the Mcrypt Encryption Functions, provide an easy way to do this and are especially useful if you need to do the operation often, because they hide the nitty-gritty details and help clean up your code.
easy_crypt()encodes a string, and takes two arguments: (1) a string to be encoded, and (2) a 'key' or 'password' that is used to decode the string later. It returns a two element array consisting of (1) the endoded string (index 0) and (2) the so-called initialization vector used to encode the string.easy_decrypt()decodes strings encoded witheasy_crypt(), and also takes two arguments: (1) an array of the type returned byeasy_crypt()and (2) the key used to 'unlock' the data. It returns the original string if the key is correct, and gibberish otherwise.
<?php
//encodes the string. Returns an array with the
//string as the first element and the initialization
//vector as the second element
function easy_crypt($string, $key){
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
$string = mcrypt_encrypt(MCRYPT_BLOWFISH, $key,
$string, MCRYPT_MODE_CBC, $iv);
return array(base64_encode($string), base64_encode($iv));
}
//decodes a string
//the first argument is an array as returned by easy_encrypt()
function easy_decrypt($cyph_arr, $key){
$out = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, base64_decode($cyph_arr[0]),
MCRYPT_MODE_CBC, base64_decode($cyph_arr[1]));
return trim($out);
}
//----------------example usage-----------------------------------------
$str = 'Super-top-secret string';
$code = 'p@$$word';
$cyph = easy_crypt($str, $code);
$dec_string = easy_decrypt($cyph, $code);
echo "The original string is: $strn";
echo "The encoded string is: {$cyph[0]}n";
echo "The initialization vector is: {$cyph[1]}n";
echo "The decoded string is $dec_stringn";
?>
So, you can easily encode a string, and store it and its initialization vector (say in a database) to be decoded later using your key. Simple as that.

