Wow! Haven’t posted in a while. I should start more frequently, I’ve had some very busy days.
As I touched on in a previous post, I was working an encryption. I had found that GnuPG (a free version of PGP – Pretty Good Privacy) could be used in PHP and was trying to get that working. I looked into it and it seemed pretty complicated and I didn’t easily have access to install the necessary modules on on Linux Hosting. Therefore I decided to look for an alternate method.
I needed two-way encryption, meaning I could encrypt and decrypt it. The PHP function crypt() is one-way encryption, and wouldn’t work for my needs. MCrypt(), however, is a two way encryption function that supports many different methods. To see what methods are available on your server, put in the phpinfo() function in a page and you will find a section called “mcrypt”. Here it will tell you what methods are available for your use.
A page from hudzilla.org goes over the main different encryption methods and what should be used for your situation. I ended up choosing rijndael-256 (256 bit encryption, which is quite powerful). The example I give below will use this method.
I have made two functions, one to encrypt a string and one to decrypt a string. Here they are:
function encrypt($string, $extra = “”)
{
/* Open the cipher */
$td = mcrypt_module_open(‘rijndael-256′, ”, ‘ecb’, ”);
/* Create the IV and determine the keysize length, used MCRYPT_RAND
* on Windows instead */
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
$ks = mcrypt_enc_get_key_size($td);
/* Create key */
$key = substr(md5(“CoMpLiCatED K3y” . $extra), 0, $ks);
/* Intialize encryption */
mcrypt_generic_init($td, $key, $iv);
/* Encrypt data */
$encrypted = mcrypt_generic($td, trim($string));
/* Terminate encryption handler */
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $encrypted;
}
Where “CoMpLiCatED K3y” is your key for encryption and decryption. The optional $extra argument is what you can append to your key. This can make something more secure and different encryption keys for different purposes. Here’s the decrypt function:
function decrypt($encrypted, $extra = “”)
{
/* Open the cipher */
$td = mcrypt_module_open(‘rijndael-256′, ”, ‘ecb’, ”);
/* Create the IV and determine the keysize length, used MCRYPT_RAND
* on Windows instead */
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
$ks = mcrypt_enc_get_key_size($td);
/* Create key */
$key = substr(md5(“CoMpLiCatED K3y” . $extra), 0, $ks);
/* Initialize encryption module for decryption */
mcrypt_generic_init($td, $key, $iv);
/* Decrypt encrypted string */
$decrypted = mdecrypt_generic($td, $encrypted);
/* Terminate decryption handle and close module */
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return trim($decrypted);
}
The same data applies to the above function, and it returns the decrypted string.
Enjoy!
-Kerry