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) 2006, 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                 $this->CI->load->library('validation');
00145                 
00146                 if ($this->CI->validation->valid_base64($string) === FALSE)
00147                 {
00148                         return FALSE;
00149                 }
00150 
00151                 $dec = base64_decode($string);
00152 
00153                 if ($this->_mcrypt_exists === TRUE)
00154                 {
00155                         if (($dec = $this->mcrypt_decode($dec, $key)) === FALSE)
00156                         {
00157                                 return FALSE;
00158                         }
00159                 }
00160                 
00161                 return $this->_xor_decode($dec, $key);
00162         }
00163         
00164         // --------------------------------------------------------------------
00165 
00166         /**
00167          * XOR Encode
00168          *
00169          * Takes a plain-text string and key as input and generates an
00170          * encoded bit-string using XOR
00171          *
00172          * @access      private
00173          * @param       string
00174          * @param       string
00175          * @return      string
00176          */     
00177         function _xor_encode($string, $key)
00178         {
00179                 $rand = '';
00180                 while (strlen($rand) < 32)
00181                 {
00182                         $rand .= mt_rand(0, mt_getrandmax());
00183                 }
00184         
00185                 $rand = $this->hash($rand);
00186                 
00187                 $enc = '';
00188                 for ($i = 0; $i < strlen($string); $i++)
00189                 {                       
00190                         $enc .= substr($rand, ($i % strlen($rand)), 1).(substr($rand, ($i % strlen($rand)), 1) ^ substr($string, $i, 1));
00191                 }
00192                                 
00193                 return $this->_xor_merge($enc, $key);
00194         }
00195         
00196         // --------------------------------------------------------------------
00197 
00198         /**
00199          * XOR Decode
00200          *
00201          * Takes an encoded string and key as input and generates the
00202          * plain-text original message
00203          *
00204          * @access      private
00205          * @param       string
00206          * @param       string
00207          * @return      string
00208          */     
00209         function _xor_decode($string, $key)
00210         {
00211                 $string = $this->_xor_merge($string, $key);
00212                 
00213                 $dec = '';
00214                 for ($i = 0; $i < strlen($string); $i++)
00215                 {
00216                         $dec .= (substr($string, $i++, 1) ^ substr($string, $i, 1));
00217                 }
00218         
00219                 return $dec;
00220         }
00221         
00222         // --------------------------------------------------------------------
00223 
00224         /**
00225          * XOR key + string Combiner
00226          *
00227          * Takes a string and key as input and computes the difference using XOR
00228          *
00229          * @access      private
00230          * @param       string
00231          * @param       string
00232          * @return      string
00233          */     
00234         function _xor_merge($string, $key)
00235         {
00236                 $hash = $this->hash($key);
00237                 $str = '';
00238                 for ($i = 0; $i < strlen($string); $i++)
00239                 {
00240                         $str .= substr($string, $i, 1) ^ substr($hash, ($i % strlen($hash)), 1);
00241                 }
00242                 
00243                 return $str;
00244         }
00245         
00246         // --------------------------------------------------------------------
00247 
00248         /**
00249          * Encrypt using Mcrypt
00250          *
00251          * @access      public
00252          * @param       string
00253          * @param       string
00254          * @return      string
00255          */
00256         function mcrypt_encode($data, $key)
00257         {       
00258                 $init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
00259                 $init_vect = mcrypt_create_iv($init_size, MCRYPT_RAND);
00260                 return $this->_add_cipher_noise($init_vect.mcrypt_encrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), $key);
00261         }
00262         
00263         // --------------------------------------------------------------------
00264 
00265         /**
00266          * Decrypt using Mcrypt
00267          *
00268          * @access      public
00269          * @param       string
00270          * @param       string
00271          * @return      string
00272          */     
00273         function mcrypt_decode($data, $key)
00274         {
00275                 $data = $this->_remove_cipher_noise($data, $key);
00276                 $init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
00277                 
00278                 if ($init_size > strlen($data))
00279                 {
00280                         return FALSE;
00281                 }
00282                 
00283                 $init_vect = substr($data, 0, $init_size);
00284                 $data = substr($data, $init_size);
00285                 return rtrim(mcrypt_decrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), "\0");
00286         }
00287         
00288         // --------------------------------------------------------------------
00289 
00290         /**
00291          * Adds permuted noise to the IV + encrypted data to protect
00292          * against Man-in-the-middle attacks on CBC mode ciphers
00293          * http://www.ciphersbyritter.com/GLOSSARY.HTM#IV
00294          *
00295          * Function description
00296          *
00297          * @access      private
00298          * @param       string
00299          * @param       string
00300          * @return      string
00301          */
00302         function _add_cipher_noise($data, $key)
00303         {
00304                 $keyhash = $this->hash($key);
00305                 $keylen = strlen($keyhash);
00306                 $str = '';
00307         
00308                 for ($i = 0, $j = 0, $len = strlen($data); $i < $len; ++$i, ++$j)
00309                 {       
00310                         if ($j >= $keylen)
00311                         {
00312                                 $j = 0;
00313                         }
00314                         
00315                         $str .= chr((ord($data[$i]) + ord($keyhash[$j])) % 256);
00316                 }
00317                 
00318                 return $str;
00319         }
00320 
00321         // --------------------------------------------------------------------
00322         
00323         /**
00324          * Removes permuted noise from the IV + encrypted data, reversing
00325          * _add_cipher_noise()
00326          *
00327          * Function description
00328          *
00329          * @access      public
00330          * @param       type
00331          * @return      type
00332          */
00333         function _remove_cipher_noise($data, $key)
00334         {
00335                 $keyhash = $this->hash($key);
00336                 $keylen = strlen($keyhash);
00337                 $str = '';
00338 
00339                 for ($i = 0, $j = 0, $len = strlen($data); $i < $len; ++$i, ++$j)
00340                 {
00341                         if ($j >= $keylen)
00342                         {
00343                                 $j = 0;
00344                         }
00345                         
00346                         $temp = ord($data[$i]) - ord($keyhash[$j]);
00347                         
00348                         if ($temp < 0)
00349                         {
00350                                 $temp = $temp + 256;
00351                         }
00352                         
00353                         $str .= chr($temp);
00354                 }
00355                 
00356                 return $str;
00357         }
00358 
00359         // --------------------------------------------------------------------
00360         
00361         /**
00362          * Set the Mcrypt Cipher
00363          *
00364          * @access      public
00365          * @param       constant
00366          * @return      string
00367          */
00368         function set_cipher($cipher)
00369         {
00370                 $this->_mcrypt_cipher = $cipher;
00371         }
00372         
00373         // --------------------------------------------------------------------
00374 
00375         /**
00376          * Set the Mcrypt Mode
00377          *
00378          * @access      public
00379          * @param       constant
00380          * @return      string
00381          */
00382         function set_mode($mode)
00383         {
00384                 $this->_mcrypt_mode = $mode;
00385         }
00386         
00387         // --------------------------------------------------------------------
00388 
00389         /**
00390          * Get Mcrypt cipher Value
00391          *
00392          * @access      private
00393          * @return      string
00394          */     
00395         function _get_cipher()
00396         {
00397                 if ($this->_mcrypt_cipher == '')
00398                 {
00399                         $this->_mcrypt_cipher = MCRYPT_RIJNDAEL_256;
00400                 }
00401 
00402                 return $this->_mcrypt_cipher;
00403         }
00404 
00405         // --------------------------------------------------------------------
00406 
00407         /**
00408          * Get Mcrypt Mode Value
00409          *
00410          * @access      private
00411          * @return      string
00412          */     
00413         function _get_mode()
00414         {
00415                 if ($this->_mcrypt_mode == '')
00416                 {
00417                         $this->_mcrypt_mode = MCRYPT_MODE_ECB;
00418                 }
00419                 
00420                 return $this->_mcrypt_mode;
00421         }
00422         
00423         // --------------------------------------------------------------------
00424 
00425         /**
00426          * Set the Hash type
00427          *
00428          * @access      public
00429          * @param       string
00430          * @return      string
00431          */             
00432         function set_hash($type = 'sha1')
00433         {
00434                 $this->_hash_type = ($type != 'sha1' AND $type != 'md5') ? 'sha1' : $type;
00435         }
00436         
00437         // --------------------------------------------------------------------
00438 
00439         /**
00440          * Hash encode a string
00441          *
00442          * @access      public
00443          * @param       string
00444          * @return      string
00445          */             
00446         function hash($str)
00447         {
00448                 return ($this->_hash_type == 'sha1') ? $this->sha1($str) : md5($str);
00449         }
00450         
00451         // --------------------------------------------------------------------
00452 
00453         /**
00454          * Generate an SHA1 Hash
00455          *
00456          * @access      public
00457          * @param       string
00458          * @return      string
00459          */     
00460         function sha1($str)
00461         {
00462                 if ( ! function_exists('sha1'))
00463                 {
00464                         if ( ! function_exists('mhash'))
00465                         {       
00466                                 require_once(BASEPATH.'libraries/Sha1'.EXT);
00467                                 $SH = new CI_SHA;
00468                                 return $SH->generate($str);
00469                         }
00470                         else
00471                         {
00472                                 return bin2hex(mhash(MHASH_SHA1, $str));
00473                         }
00474                 }
00475                 else
00476                 {
00477                         return sha1($str);
00478                 }       
00479         }
00480         
00481 }
00482 
00483 // END CI_Encrypt class
00484 
00485 /* End of file Encrypt.php */
00486 /* Location: ./system/libraries/Encrypt.php */