Encrypting string with PHP using mcrypt

A simple class to encrypt-decrypt strings

Date: 7-dec-2009

You may need a simple class like this to make work mcrypt. The iv value should remain static to make it all work.

The bin2hex function convertsto an hexadecimal string to get URL-Safe data.To be safely used in, for example in a URL, to avoid problems with reserved characters like '&'. You need alphanumeric characters – like hexadecimal string are.

The trim the return values in the methods to trim the nulls and EOTs (End of Transmission) at the end.

/**
* Crypt.class.php
*
* A class to Encrypt/Decrypt Strings
* The encrypted output can be used in URLs, emails, etc
*
* - Sample use:

*   $objCrypt=new Crypt();
*    
*   // Show encrypted values only
*   $encryptedId=$objCrypt->encrypt($my_id_to_hide);
*    
*   // Process in your server side script the decrypted value
*   $decryptedId=$objCrypt->decrypt($encryptedId);
* @author http://freedelta.free.fr
*/
class Crypt { protected $securekey; private static $iv=null; function __construct() { $textkey="MySecretTextKey"; $this->setKey(substr(md5($textkey),0,12)); } /* Get only one instance */ static public function getIv() { if(self::$iv==null) { $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); self::$iv=mcrypt_create_iv($iv_size, MCRYPT_RAND); } return self::$iv; } /**
* Encrypts query string to pass it as GET or POST parameters safely
* special characters like '&', or '%' will be excluded
*
* @param query string
* @return String hexadecimal encrypted query string
*/


function encrypt($input)
{
if(strlen(trim($input))==0)
       {
            return "";
       }
 return $this->hexFromBin(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->getKey(), $input, MCRYPT_MODE_ECB, self::getIv()));
}

/**
* Decrypts query string comming from GET or POST parameters
*
* @param Querystring
* @return String Decrypted query string
*/
function decrypt($input) { if(strlen(trim($input))==0)
       {
            return "";
       }

return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->getKey(), $this->binFromHex($input), MCRYPT_MODE_ECB, self::getIv())); } /**
* Converts binary string to hexadecimal
*
* @param string binary
* @return string hexadecimal
*/

public function hexFromBin($data)
{
return bin2hex($data);
}

/**
* Converts hexadecimal string to binary
*
* @param string hexadecimal
* @return string binary converted
*/

function binFromHex($data)
{
$len = strlen($data);
return pack("H" . $len, $data);
}


/* Getters/Setters */ public function getKey() { return $this->securekey; } public function setKey($securekey) { $this->securekey=$securekey; } }