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.

<?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.


post to Dzone Digg this! Add to del.icio.us Googleize this Add to reddit Save to myYahoo Add to furl Add to Netvouz! Spurl this! Add to Linkroll! Save to Simpy Give if thumbs up on StumbleUpon Save to Blinklist Add to Tektag Save to Bibsonomy Submit to Tweako
Search ERT on the Tools Page
Did you know? You can discuss this article with the mentor who wrote it and others interested in the topic? You are invited to join the discussion with Go to the forum

Got a technical article or tutorial you want to publish on the Internet? Join Go to the forum in the Round Table Forum and let the Mentors know what you have. If it meets ERT standards, is factual and can help ERT visitors, then ERT Mentors and Editors can help you (without charge) polish your offering so it can be published and promoted by ERT. An article published on ERT may be read by as many as 10,000 visitors a week; promoting you, your site, and your ideas. Please note ERT does not publish re-prints; promotional handouts, or pieces consisting mainly of links. So original technical content only please. If you prefer you can email the Editor