blob: ccc470c2b1cbe62ea14092fd54ef808a1d486731 [file] [log] [blame]
Derek Allardd2df9bc2007-04-15 17:41:17 +00001<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
2/**
3 * CodeIgniter
4 *
5 * An open source application development framework for PHP 4.3.2 or newer
6 *
7 * @package CodeIgniter
Derek Allard3d879d52008-01-18 19:41:32 +00008 * @author ExpressionEngine Dev Team
Derek Allardd2df9bc2007-04-15 17:41:17 +00009 * @copyright Copyright (c) 2006, EllisLab, Inc.
Derek Allard6838f002007-10-04 19:29:59 +000010 * @license http://www.codeigniter.com/user_guide/license.html
Derek Allardd2df9bc2007-04-15 17:41:17 +000011 * @link http://www.codeigniter.com
12 * @since Version 1.0
13 * @filesource
14 */
15
16// ------------------------------------------------------------------------
17
18/**
19 * CodeIgniter Encryption Class
20 *
21 * Provides two-way keyed encoding using XOR Hashing and Mcrypt
22 *
23 * @package CodeIgniter
24 * @subpackage Libraries
25 * @category Libraries
Derek Allard3d879d52008-01-18 19:41:32 +000026 * @author ExpressionEngine Dev Team
Derek Allardd2df9bc2007-04-15 17:41:17 +000027 * @link http://www.codeigniter.com/user_guide/libraries/encryption.html
28 */
29class CI_Encrypt {
30
31 var $encryption_key = '';
32 var $_hash_type = 'sha1';
33 var $_mcrypt_exists = FALSE;
34 var $_mcrypt_cipher;
35 var $_mcrypt_mode;
36
37 /**
38 * Constructor
39 *
40 * Simply determines whether the mcrypt library exists.
41 *
42 */
43 function CI_Encrypt()
44 {
45 $this->_mcrypt_exists = ( ! function_exists('mcrypt_encrypt')) ? FALSE : TRUE;
46 log_message('debug', "Encrypt Class Initialized");
47 }
48
49 // --------------------------------------------------------------------
50
51 /**
52 * Fetch the encryption key
53 *
54 * Returns it as MD5 in order to have an exact-length 128 bit key.
55 * Mcrypt is sensitive to keys that are not the correct length
56 *
57 * @access public
58 * @param string
59 * @return string
60 */
61 function get_key($key = '')
62 {
63 if ($key == '')
64 {
65 if ($this->encryption_key != '')
66 {
67 return $this->encryption_key;
68 }
69
70 $CI =& get_instance();
71 $key = $CI->config->item('encryption_key');
72
73 if ($key === FALSE)
74 {
75 show_error('In order to use the encryption class requires that you set an encryption key in your config file.');
76 }
77 }
78
79 return md5($key);
80 }
81
82 // --------------------------------------------------------------------
83
84 /**
85 * Set the encryption key
86 *
87 * @access public
88 * @param string
89 * @return void
90 */
91 function set_key($key = '')
92 {
93 $this->encryption_key = $key;
94 }
95
96 // --------------------------------------------------------------------
97
98 /**
99 * Encode
100 *
101 * Encodes the message string using bitwise XOR encoding.
102 * The key is combined with a random hash, and then it
103 * too gets converted using XOR. The whole thing is then run
104 * through mcrypt (if supported) using the randomized key.
105 * The end result is a double-encrypted message string
106 * that is randomized with each call to this function,
107 * even if the supplied message and key are the same.
108 *
109 * @access public
110 * @param string the string to encode
111 * @param string the key
112 * @return string
113 */
114 function encode($string, $key = '')
115 {
116 $key = $this->get_key($key);
117 $enc = $this->_xor_encode($string, $key);
118
119 if ($this->_mcrypt_exists === TRUE)
120 {
121 $enc = $this->mcrypt_encode($enc, $key);
122 }
123 return base64_encode($enc);
124 }
125
126 // --------------------------------------------------------------------
127
128 /**
129 * Decode
130 *
131 * Reverses the above process
132 *
133 * @access public
134 * @param string
135 * @param string
136 * @return string
137 */
138 function decode($string, $key = '')
139 {
140 $key = $this->get_key($key);
141 $dec = base64_decode($string);
142
143 if ($dec === FALSE)
144 {
145 return FALSE;
146 }
147
148 if ($this->_mcrypt_exists === TRUE)
149 {
150 $dec = $this->mcrypt_decode($dec, $key);
151 }
152
153 return $this->_xor_decode($dec, $key);
154 }
155
156 // --------------------------------------------------------------------
157
158 /**
159 * XOR Encode
160 *
161 * Takes a plain-text string and key as input and generates an
162 * encoded bit-string using XOR
163 *
164 * @access private
165 * @param string
166 * @param string
167 * @return string
168 */
169 function _xor_encode($string, $key)
170 {
171 $rand = '';
172 while (strlen($rand) < 32)
173 {
174 $rand .= mt_rand(0, mt_getrandmax());
175 }
176
177 $rand = $this->hash($rand);
178
179 $enc = '';
180 for ($i = 0; $i < strlen($string); $i++)
181 {
182 $enc .= substr($rand, ($i % strlen($rand)), 1).(substr($rand, ($i % strlen($rand)), 1) ^ substr($string, $i, 1));
183 }
184
185 return $this->_xor_merge($enc, $key);
186 }
187
188 // --------------------------------------------------------------------
189
190 /**
191 * XOR Decode
192 *
193 * Takes an encoded string and key as input and generates the
194 * plain-text original message
195 *
196 * @access private
197 * @param string
198 * @param string
199 * @return string
200 */
201 function _xor_decode($string, $key)
202 {
203 $string = $this->_xor_merge($string, $key);
204
205 $dec = '';
206 for ($i = 0; $i < strlen($string); $i++)
207 {
208 $dec .= (substr($string, $i++, 1) ^ substr($string, $i, 1));
209 }
210
211 return $dec;
212 }
213
214 // --------------------------------------------------------------------
215
216 /**
217 * XOR key + string Combiner
218 *
219 * Takes a string and key as input and computes the difference using XOR
220 *
221 * @access private
222 * @param string
223 * @param string
224 * @return string
225 */
226 function _xor_merge($string, $key)
227 {
228 $hash = $this->hash($key);
229 $str = '';
230 for ($i = 0; $i < strlen($string); $i++)
231 {
232 $str .= substr($string, $i, 1) ^ substr($hash, ($i % strlen($hash)), 1);
233 }
234
235 return $str;
236 }
237
238 // --------------------------------------------------------------------
239
240 /**
241 * Encrypt using Mcrypt
242 *
243 * @access public
244 * @param string
245 * @param string
246 * @return string
247 */
248 function mcrypt_encode($data, $key)
249 {
250 $init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
251 $init_vect = mcrypt_create_iv($init_size, MCRYPT_RAND);
Derek Jonesd32d45c2008-01-17 19:21:03 +0000252 return $this->_add_cipher_noise($init_vect.mcrypt_encrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), $key);
Derek Allardd2df9bc2007-04-15 17:41:17 +0000253 }
254
255 // --------------------------------------------------------------------
256
257 /**
258 * Decrypt using Mcrypt
259 *
260 * @access public
261 * @param string
262 * @param string
263 * @return string
264 */
265 function mcrypt_decode($data, $key)
266 {
Derek Jonesd32d45c2008-01-17 19:21:03 +0000267 $data = $this->_remove_cipher_noise($data, $key);
Derek Allardd2df9bc2007-04-15 17:41:17 +0000268 $init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
Derek Jonesd32d45c2008-01-17 19:21:03 +0000269 $init_vect = substr($data, 0, $init_size);
270 $data = substr($data, $init_size);
Derek Allardd2df9bc2007-04-15 17:41:17 +0000271 return rtrim(mcrypt_decrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), "\0");
272 }
273
274 // --------------------------------------------------------------------
275
276 /**
Derek Jonesd32d45c2008-01-17 19:21:03 +0000277 * Adds permuted noise to the IV + encrypted data to protect
278 * against Man-in-the-middle attacks on CBC mode ciphers
279 * http://www.ciphersbyritter.com/GLOSSARY.HTM#IV
280 *
281 * Function description
282 *
283 * @access private
284 * @param string
285 * @param string
286 * @return string
287 */
288 function _add_cipher_noise($data, $key)
289 {
290 $keyhash = $this->hash($key);
291 $keylen = strlen($keyhash);
292 $str = '';
293
294 for ($i = 0, $j = 0, $len = strlen($data); $i < $len; ++$i, ++$j)
295 {
296 if ($j >= $keylen)
297 {
298 $j = 0;
299 }
300
301 $str .= chr((ord($data[$i]) + ord($keyhash[$j])) % 256);
302 }
303
304 return $str;
305 }
306
307 // --------------------------------------------------------------------
308
309 /**
310 * Removes permuted noise from the IV + encrypted data, reversing
311 * _add_cipher_noise()
312 *
313 * Function description
314 *
315 * @access public
316 * @param type
317 * @return type
318 */
319 function _remove_cipher_noise($data, $key)
320 {
321 $keyhash = $this->hash($key);
322 $keylen = strlen($keyhash);
323 $str = '';
324
325 for ($i = 0, $j = 0, $len = strlen($data); $i < $len; ++$i, ++$j)
326 {
327 if ($j >= $keylen)
328 {
329 $j = 0;
330 }
331
332 $temp = ord($data[$i]) - ord($keyhash[$j]);
333
334 if ($temp < 0)
335 {
336 $temp = $temp + 256;
337 }
338
339 $str .= chr($temp);
340 }
341
342 return $str;
343 }
344
345 // --------------------------------------------------------------------
346
347 /**
Derek Allardd2df9bc2007-04-15 17:41:17 +0000348 * Set the Mcrypt Cipher
349 *
350 * @access public
351 * @param constant
352 * @return string
353 */
354 function set_cipher($cipher)
355 {
356 $this->_mcrypt_cipher = $cipher;
357 }
358
359 // --------------------------------------------------------------------
360
361 /**
362 * Set the Mcrypt Mode
363 *
364 * @access public
365 * @param constant
366 * @return string
367 */
368 function set_mode($mode)
369 {
370 $this->_mcrypt_mode = $mode;
371 }
372
373 // --------------------------------------------------------------------
374
375 /**
376 * Get Mcrypt cipher Value
377 *
378 * @access private
379 * @return string
380 */
381 function _get_cipher()
382 {
383 if ($this->_mcrypt_cipher == '')
384 {
385 $this->_mcrypt_cipher = MCRYPT_RIJNDAEL_256;
386 }
387
388 return $this->_mcrypt_cipher;
389 }
390
391 // --------------------------------------------------------------------
392
393 /**
Derek Allard83ec2402007-06-18 00:14:44 +0000394 * Get Mcrypt Mode Value
Derek Allardd2df9bc2007-04-15 17:41:17 +0000395 *
396 * @access private
397 * @return string
398 */
399 function _get_mode()
400 {
401 if ($this->_mcrypt_mode == '')
402 {
403 $this->_mcrypt_mode = MCRYPT_MODE_ECB;
404 }
405
406 return $this->_mcrypt_mode;
407 }
408
409 // --------------------------------------------------------------------
410
411 /**
412 * Set the Hash type
413 *
414 * @access public
415 * @param string
416 * @return string
417 */
418 function set_hash($type = 'sha1')
419 {
420 $this->_hash_type = ($type != 'sha1' AND $type != 'md5') ? 'sha1' : $type;
421 }
422
423 // --------------------------------------------------------------------
424
425 /**
426 * Hash encode a string
427 *
428 * @access public
429 * @param string
430 * @return string
431 */
432 function hash($str)
433 {
434 return ($this->_hash_type == 'sha1') ? $this->sha1($str) : md5($str);
435 }
436
437 // --------------------------------------------------------------------
438
439 /**
440 * Generate an SHA1 Hash
441 *
442 * @access public
443 * @param string
444 * @return string
445 */
446 function sha1($str)
447 {
448 if ( ! function_exists('sha1'))
449 {
450 if ( ! function_exists('mhash'))
451 {
452 require_once(BASEPATH.'libraries/Sha1'.EXT);
453 $SH = new CI_SHA;
454 return $SH->generate($str);
455 }
456 else
457 {
458 return bin2hex(mhash(MHASH_SHA1, $str));
459 }
460 }
461 else
462 {
463 return sha1($str);
464 }
465 }
466
467}
468
469// END CI_Encrypt class
adminb0dd10f2006-08-25 17:25:49 +0000470?>