Encrypt.php

Go to the documentation of this file.
00001 <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
00002 /**
00003  * CodeIgniter
00004  *
00005  * An open source application development framework for PHP 4.3.2 or newer
00006  *
00007  * @package             CodeIgniter
00008  * @author              ExpressionEngine Dev Team
00009  * @copyright   Copyright (c) 2008, EllisLab, Inc.
00010  * @license             http://codeigniter.com/user_guide/license.html
00011  * @link                http://codeigniter.com
00012  * @since               Version 1.0
00013  * @filesource
00014  */
00015 
00016 // ------------------------------------------------------------------------
00017 
00018 /**
00019  * CodeIgniter Encryption Class
00020  *
00021  * Provides two-way keyed encoding using XOR Hashing and Mcrypt
00022  *
00023  * @package             CodeIgniter
00024  * @subpackage  Libraries
00025  * @category    Libraries
00026  * @author              ExpressionEngine Dev Team
00027  * @link                http://codeigniter.com/user_guide/libraries/encryption.html
00028  */
00029 class CI_Encrypt {
00030 
00031         var $CI;
00032         var $encryption_key     = '';
00033         var $_hash_type = 'sha1';
00034         var $_mcrypt_exists = FALSE;
00035         var $_mcrypt_cipher;
00036         var $_mcrypt_mode;
00037 
00038         /**
00039          * Constructor
00040          *
00041          * Simply determines whether the mcrypt library exists.
00042          *
00043          */
00044         function CI_Encrypt()
00045         {
00046                 $this->CI =& get_instance();
00047                 $this->_mcrypt_exists = ( ! function_exists('mcrypt_encrypt')) ? FALSE : TRUE;
00048                 log_message('debug', "Encrypt Class Initialized");
00049         }
00050 
00051         // --------------------------------------------------------------------
00052 
00053         /**
00054          * Fetch the encryption key
00055          *
00056          * Returns it as MD5 in order to have an exact-length 128 bit key.
00057          * Mcrypt is sensitive to keys that are not the correct length
00058          *
00059          * @access      public
00060          * @param       string
00061          * @return      string
00062          */
00063         function get_key($key = '')
00064         {
00065                 if ($key == '')
00066                 {
00067                         if ($this->encryption_key != '')
00068                         {
00069                                 return $this->encryption_key;
00070                         }
00071 
00072                         $CI =& get_instance();
00073                         $key = $CI->config->item('encryption_key');
00074 
00075                         if ($key === FALSE)
00076                         {
00077                                 show_error('In order to use the encryption class requires that you set an encryption key in your config file.');
00078                         }
00079                 }
00080 
00081                 return md5($key);
00082         }
00083 
00084         // --------------------------------------------------------------------
00085 
00086         /**
00087          * Set the encryption key
00088          *
00089          * @access      public
00090          * @param       string
00091          * @return      void
00092          */
00093         function set_key($key = '')
00094         {
00095                 $this->encryption_key = $key;
00096         }
00097 
00098         // --------------------------------------------------------------------
00099 
00100         /**
00101          * Encode
00102          *
00103          * Encodes the message string using bitwise XOR encoding.
00104          * The key is combined with a random hash, and then it
00105          * too gets converted using XOR. The whole thing is then run
00106          * through mcrypt (if supported) using the randomized key.
00107          * The end result is a double-encrypted message string
00108          * that is randomized with each call to this function,
00109          * even if the supplied message and key are the same.
00110          *
00111          * @access      public
00112          * @param       string  the string to encode
00113          * @param       string  the key
00114          * @return      string
00115          */
00116         function encode($string, $key = '')
00117         {
00118                 $key = $this->get_key($key);
00119                 $enc = $this->_xor_encode($string, $key);
00120                 
00121                 if ($this->_mcrypt_exists === TRUE)
00122                 {
00123                         $enc = $this->mcrypt_encode($enc, $key);
00124                 }
00125                 return base64_encode($enc);
00126         }
00127 
00128         // --------------------------------------------------------------------
00129 
00130         /**
00131          * Decode
00132          *
00133          * Reverses the above process
00134          *
00135          * @access      public
00136          * @param       string
00137          * @param       string
00138          * @return      string
00139          */
00140         function decode($string, $key = '')
00141         {
00142                 $key = $this->get_key($key);
00143                 
00144                 if (preg_match('/[^a-zA-Z0-9\/\+=]/', $string))
00145                 {
00146                         return FALSE;
00147                 }
00148 
00149                 $dec = base64_decode($string);
00150 
00151                 if ($this->_mcrypt_exists === TRUE)
00152                 {
00153                         if (($dec = $this->mcrypt_decode($dec, $key)) === FALSE)
00154                         {
00155                                 return FALSE;
00156                         }
00157                 }
00158 
00159                 return $this->_xor_decode($dec, $key);
00160         }
00161 
00162         // --------------------------------------------------------------------
00163 
00164         /**
00165          * XOR Encode
00166          *
00167          * Takes a plain-text string and key as input and generates an
00168          * encoded bit-string using XOR
00169          *
00170          * @access      private
00171          * @param       string
00172          * @param       string
00173          * @return      string
00174          */
00175         function _xor_encode($string, $key)
00176         {
00177                 $rand = '';
00178                 while (strlen($rand) < 32)
00179                 {
00180                         $rand .= mt_rand(0, mt_getrandmax());
00181                 }
00182 
00183                 $rand = $this->hash($rand);
00184 
00185                 $enc = '';
00186                 for ($i = 0; $i < strlen($string); $i++)
00187                 {                       
00188                         $enc .= substr($rand, ($i % strlen($rand)), 1).(substr($rand, ($i % strlen($rand)), 1) ^ substr($string, $i, 1));
00189                 }
00190 
00191                 return $this->_xor_merge($enc, $key);
00192         }
00193 
00194         // --------------------------------------------------------------------
00195 
00196         /**
00197          * XOR Decode
00198          *
00199          * Takes an encoded string and key as input and generates the
00200          * plain-text original message
00201          *
00202          * @access      private
00203          * @param       string
00204          * @param       string
00205          * @return      string
00206          */
00207         function _xor_decode($string, $key)
00208         {
00209                 $string = $this->_xor_merge($string, $key);
00210 
00211                 $dec = '';
00212                 for ($i = 0; $i < strlen($string); $i++)
00213                 {
00214                         $dec .= (substr($string, $i++, 1) ^ substr($string, $i, 1));
00215                 }
00216 
00217                 return $dec;
00218         }
00219 
00220         // --------------------------------------------------------------------
00221 
00222         /**
00223          * XOR key + string Combiner
00224          *
00225          * Takes a string and key as input and computes the difference using XOR
00226          *
00227          * @access      private
00228          * @param       string
00229          * @param       string
00230          * @return      string
00231          */
00232         function _xor_merge($string, $key)
00233         {
00234                 $hash = $this->hash($key);
00235                 $str = '';
00236                 for ($i = 0; $i < strlen($string); $i++)
00237                 {
00238                         $str .= substr($string, $i, 1) ^ substr($hash, ($i % strlen($hash)), 1);
00239                 }
00240 
00241                 return $str;
00242         }
00243 
00244         // --------------------------------------------------------------------
00245 
00246         /**
00247          * Encrypt using Mcrypt
00248          *
00249          * @access      public
00250          * @param       string
00251          * @param       string
00252          * @return      string
00253          */
00254         function mcrypt_encode($data, $key)
00255         {
00256                 $init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
00257                 $init_vect = mcrypt_create_iv($init_size, MCRYPT_RAND);
00258                 return $this->_add_cipher_noise($init_vect.mcrypt_encrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), $key);
00259         }
00260 
00261         // --------------------------------------------------------------------
00262 
00263         /**
00264          * Decrypt using Mcrypt
00265          *
00266          * @access      public
00267          * @param       string
00268          * @param       string
00269          * @return      string
00270          */
00271         function mcrypt_decode($data, $key)
00272         {
00273                 $data = $this->_remove_cipher_noise($data, $key);
00274                 $init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
00275 
00276                 if ($init_size > strlen($data))
00277                 {
00278                         return FALSE;
00279                 }
00280 
00281                 $init_vect = substr($data, 0, $init_size);
00282                 $data = substr($data, $init_size);
00283                 return rtrim(mcrypt_decrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), "\0");
00284         }
00285 
00286         // --------------------------------------------------------------------
00287 
00288         /**
00289          * Adds permuted noise to the IV + encrypted data to protect
00290          * against Man-in-the-middle attacks on CBC mode ciphers
00291          * http://www.ciphersbyritter.com/GLOSSARY.HTM#IV
00292          *
00293          * Function description
00294          *
00295          * @access      private
00296          * @param       string
00297          * @param       string
00298          * @return      string
00299          */
00300         function _add_cipher_noise($data, $key)
00301         {
00302                 $keyhash = $this->hash($key);
00303                 $keylen = strlen($keyhash);
00304                 $str = '';
00305 
00306                 for ($i = 0, $j = 0, $len = strlen($data); $i < $len; ++$i, ++$j)
00307                 {
00308                         if ($j >= $keylen)
00309                         {
00310                                 $j = 0;
00311                         }
00312 
00313                         $str .= chr((ord($data[$i]) + ord($keyhash[$j])) % 256);
00314                 }
00315 
00316                 return $str;
00317         }
00318 
00319         // --------------------------------------------------------------------
00320 
00321         /**
00322          * Removes permuted noise from the IV + encrypted data, reversing
00323          * _add_cipher_noise()
00324          *
00325          * Function description
00326          *
00327          * @access      public
00328          * @param       type
00329          * @return      type
00330          */
00331         function _remove_cipher_noise($data, $key)
00332         {
00333                 $keyhash = $this->hash($key);
00334                 $keylen = strlen($keyhash);
00335                 $str = '';
00336 
00337                 for ($i = 0, $j = 0, $len = strlen($data); $i < $len; ++$i, ++$j)
00338                 {
00339                         if ($j >= $keylen)
00340                         {
00341                                 $j = 0;
00342                         }
00343 
00344                         $temp = ord($data[$i]) - ord($keyhash[$j]);
00345 
00346                         if ($temp < 0)
00347                         {
00348                                 $temp = $temp + 256;
00349                         }
00350                         
00351                         $str .= chr($temp);
00352                 }
00353 
00354                 return $str;
00355         }
00356 
00357         // --------------------------------------------------------------------
00358         
00359         /**
00360          * Set the Mcrypt Cipher
00361          *
00362          * @access      public
00363          * @param       constant
00364          * @return      string
00365          */
00366         function set_cipher($cipher)
00367         {
00368                 $this->_mcrypt_cipher = $cipher;
00369         }
00370 
00371         // --------------------------------------------------------------------
00372 
00373         /**
00374          * Set the Mcrypt Mode
00375          *
00376          * @access      public
00377          * @param       constant
00378          * @return      string
00379          */
00380         function set_mode($mode)
00381         {
00382                 $this->_mcrypt_mode = $mode;
00383         }
00384 
00385         // --------------------------------------------------------------------
00386 
00387         /**
00388          * Get Mcrypt cipher Value
00389          *
00390          * @access      private
00391          * @return      string
00392          */
00393         function _get_cipher()
00394         {
00395                 if ($this->_mcrypt_cipher == '')
00396                 {
00397                         $this->_mcrypt_cipher = MCRYPT_RIJNDAEL_256;
00398                 }
00399 
00400                 return $this->_mcrypt_cipher;
00401         }
00402 
00403         // --------------------------------------------------------------------
00404 
00405         /**
00406          * Get Mcrypt Mode Value
00407          *
00408          * @access      private
00409          * @return      string
00410          */
00411         function _get_mode()
00412         {
00413                 if ($this->_mcrypt_mode == '')
00414                 {
00415                         $this->_mcrypt_mode = MCRYPT_MODE_ECB;
00416                 }
00417                 
00418                 return $this->_mcrypt_mode;
00419         }
00420 
00421         // --------------------------------------------------------------------
00422 
00423         /**
00424          * Set the Hash type
00425          *
00426          * @access      public
00427          * @param       string
00428          * @return      string
00429          */
00430         function set_hash($type = 'sha1')
00431         {
00432                 $this->_hash_type = ($type != 'sha1' AND $type != 'md5') ? 'sha1' : $type;
00433         }
00434 
00435         // --------------------------------------------------------------------
00436 
00437         /**
00438          * Hash encode a string
00439          *
00440          * @access      public
00441          * @param       string
00442          * @return      string
00443          */     
00444         function hash($str)
00445         {
00446                 return ($this->_hash_type == 'sha1') ? $this->sha1($str) : md5($str);
00447         }
00448 
00449         // --------------------------------------------------------------------
00450 
00451         /**
00452          * Generate an SHA1 Hash
00453          *
00454          * @access      public
00455          * @param       string
00456          * @return      string
00457          */
00458         function sha1($str)
00459         {
00460                 if ( ! function_exists('sha1'))
00461                 {
00462                         if ( ! function_exists('mhash'))
00463                         {
00464                                 require_once(BASEPATH.'libraries/Sha1'.EXT);
00465                                 $SH = new CI_SHA;
00466                                 return $SH->generate($str);
00467                         }
00468                         else
00469                         {
00470                                 return bin2hex(mhash(MHASH_SHA1, $str));
00471                         }
00472                 }
00473                 else
00474                 {
00475                         return sha1($str);
00476                 }
00477         }
00478 
00479 }
00480 
00481 // END CI_Encrypt class
00482 
00483 /* End of file Encrypt.php */
00484 /* Location: ./system/libraries/Encrypt.php */