blob: fe8434c46185f2177cefafe5c382d24e06036e64 [file] [log] [blame]
Andrey Andreev818aedb2014-02-03 11:30:25 +02001<?php
2/**
3 * CodeIgniter
4 *
5 * An open source application development framework for PHP 5.2.4 or newer
6 *
Andrey Andreevbdb96ca2014-10-28 00:13:31 +02007 * This content is released under the MIT License (MIT)
Andrey Andreev818aedb2014-02-03 11:30:25 +02008 *
Andrey Andreevbdb96ca2014-10-28 00:13:31 +02009 * Copyright (c) 2014, British Columbia Institute of Technology
Andrey Andreev818aedb2014-02-03 11:30:25 +020010 *
Andrey Andreevbdb96ca2014-10-28 00:13:31 +020011 * Permission is hereby granted, free of charge, to any person obtaining a copy
12 * of this software and associated documentation files (the "Software"), to deal
13 * in the Software without restriction, including without limitation the rights
14 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 * copies of the Software, and to permit persons to whom the Software is
16 * furnished to do so, subject to the following conditions:
Andrey Andreev818aedb2014-02-03 11:30:25 +020017 *
Andrey Andreevbdb96ca2014-10-28 00:13:31 +020018 * The above copyright notice and this permission notice shall be included in
19 * all copies or substantial portions of the Software.
20 *
21 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27 * THE SOFTWARE.
28 *
29 * @package CodeIgniter
30 * @author EllisLab Dev Team
darwinel871754a2014-02-11 17:34:57 +010031 * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
Andrey Andreevbdb96ca2014-10-28 00:13:31 +020032 * @copyright Copyright (c) 2014, British Columbia Institute of Technology (http://bcit.ca/)
33 * @license http://opensource.org/licenses/MIT MIT License
34 * @link http://codeigniter.com
35 * @since Version 3.0.0
Andrey Andreev818aedb2014-02-03 11:30:25 +020036 * @filesource
37 */
38defined('BASEPATH') OR exit('No direct script access allowed');
39
40/**
41 * CodeIgniter Encryption Class
42 *
43 * Provides two-way keyed encryption via PHP's MCrypt and/or OpenSSL extensions.
44 *
45 * @package CodeIgniter
46 * @subpackage Libraries
47 * @category Libraries
48 * @author Andrey Andreev
49 * @link http://codeigniter.com/user_guide/libraries/encryption.html
50 */
51class CI_Encryption {
52
53 /**
54 * Encryption cipher
55 *
56 * @var string
57 */
Andrey Andreev81e10642014-02-07 01:43:36 +020058 protected $_cipher = 'aes-128';
Andrey Andreev818aedb2014-02-03 11:30:25 +020059
60 /**
61 * Cipher mode
62 *
63 * @var string
64 */
65 protected $_mode = 'cbc';
66
67 /**
68 * Cipher handle
69 *
70 * @var mixed
71 */
72 protected $_handle;
73
74 /**
75 * Encryption key
76 *
77 * @var string
78 */
79 protected $_key;
80
81 /**
82 * PHP extension to be used
83 *
84 * @var string
85 */
86 protected $_driver;
87
88 /**
89 * List of usable drivers (PHP extensions)
90 *
91 * @var array
92 */
93 protected $_drivers = array();
94
Andrey Andreev29cade42014-02-04 14:05:58 +020095 /**
Andrey Andreevf4017672014-02-05 18:51:15 +020096 * List of available modes
97 *
98 * @var array
99 */
100 protected $_modes = array(
101 'mcrypt' => array(
102 'cbc' => 'cbc',
103 'ecb' => 'ecb',
104 'ofb' => 'nofb',
105 'ofb8' => 'ofb',
106 'cfb' => 'ncfb',
107 'cfb8' => 'cfb',
108 'ctr' => 'ctr',
109 'stream' => 'stream'
110 ),
111 'openssl' => array(
112 'cbc' => 'cbc',
113 'ecb' => 'ecb',
114 'ofb' => 'ofb',
115 'cfb' => 'cfb',
116 'cfb8' => 'cfb8',
117 'ctr' => 'ctr',
118 'stream' => '',
Andrey Andreevf4017672014-02-05 18:51:15 +0200119 'xts' => 'xts'
120 )
121 );
122
123 /**
Andrey Andreev29cade42014-02-04 14:05:58 +0200124 * List of supported HMAC algorightms
125 *
126 * name => digest size pairs
127 *
128 * @var array
129 */
130 protected $_digests = array(
131 'sha224' => 28,
132 'sha256' => 32,
133 'sha384' => 48,
134 'sha512' => 64
135 );
136
Andrey Andreev2da35502014-07-07 14:41:57 +0300137 /**
138 * mbstring.func_override flag
139 *
140 * @var bool
141 */
142 protected static $func_override;
143
Andrey Andreev818aedb2014-02-03 11:30:25 +0200144 // --------------------------------------------------------------------
145
146 /**
147 * Class constructor
148 *
149 * @param array $params Configuration parameters
150 * @return void
151 */
152 public function __construct(array $params = array())
153 {
154 $this->_drivers = array(
Andrey Andreev8e202162014-02-05 18:59:55 +0200155 'mcrypt' => defined('MCRYPT_DEV_URANDOM'),
Andrey Andreev818aedb2014-02-03 11:30:25 +0200156 // While OpenSSL is available for PHP 5.3.0, an IV parameter
157 // for the encrypt/decrypt functions is only available since 5.3.3
158 'openssl' => (is_php('5.3.3') && extension_loaded('openssl'))
159 );
160
161 if ( ! $this->_drivers['mcrypt'] && ! $this->_drivers['openssl'])
162 {
163 return show_error('Encryption: Unable to find an available encryption driver.');
164 }
165
Andrey Andreev2da35502014-07-07 14:41:57 +0300166 isset(self::$func_override) OR self::$func_override = (extension_loaded('mbstring') && ini_get('mbstring.func_override'));
Andrey Andreev818aedb2014-02-03 11:30:25 +0200167 $this->initialize($params);
Andrey Andreev2da35502014-07-07 14:41:57 +0300168
169 if ( ! isset($this->_key) && self::strlen($key = config_item('encryption_key')) > 0)
Andrey Andreev818aedb2014-02-03 11:30:25 +0200170 {
Andrey Andreev81e10642014-02-07 01:43:36 +0200171 $this->_key = $key;
Andrey Andreev818aedb2014-02-03 11:30:25 +0200172 }
173
174 log_message('debug', 'Encryption Class Initialized');
175 }
176
177 // --------------------------------------------------------------------
178
179 /**
180 * Initialize
181 *
182 * @param array $params Configuration parameters
183 * @return CI_Encryption
184 */
185 public function initialize(array $params)
186 {
187 if ( ! empty($params['driver']))
188 {
189 if (isset($this->_drivers[$params['driver']]))
190 {
Andrey Andreev50ccc382014-02-04 23:30:06 +0200191 if ($this->_drivers[$params['driver']])
Andrey Andreev818aedb2014-02-03 11:30:25 +0200192 {
193 $this->_driver = $params['driver'];
194 }
195 else
196 {
197 log_message('error', "Encryption: Driver '".$params['driver']."' is not available.");
198 }
199 }
200 else
201 {
202 log_message('error', "Encryption: Unknown driver '".$params['driver']."' cannot be configured.");
203 }
204 }
205
Andrey Andreev912831f2014-02-04 17:21:37 +0200206 if (empty($this->_driver))
207 {
Andrey Andreev8e202162014-02-05 18:59:55 +0200208 $this->_driver = ($this->_drivers['openssl'] === TRUE)
209 ? 'openssl'
210 : 'mcrypt';
Andrey Andreev912831f2014-02-04 17:21:37 +0200211
212 log_message('debug', "Encryption: Auto-configured driver '".$this->_driver."'.");
213 }
214
Andrey Andreev818aedb2014-02-03 11:30:25 +0200215 empty($params['key']) OR $this->_key = $params['key'];
216 $this->{'_'.$this->_driver.'_initialize'}($params);
217 return $this;
218 }
219
220 // --------------------------------------------------------------------
221
222 /**
223 * Initialize MCrypt
224 *
225 * @param array $params Configuration parameters
226 * @return void
227 */
228 protected function _mcrypt_initialize($params)
229 {
230 if ( ! empty($params['cipher']))
231 {
232 $params['cipher'] = strtolower($params['cipher']);
233 $this->_cipher_alias($params['cipher']);
234
235 if ( ! in_array($params['cipher'], mcrypt_list_algorithms(), TRUE))
236 {
237 log_message('error', 'Encryption: MCrypt cipher '.strtoupper($params['cipher']).' is not available.');
238 }
239 else
240 {
241 $this->_cipher = $params['cipher'];
242 }
243 }
244
245 if ( ! empty($params['mode']))
246 {
Andrey Andreevf4017672014-02-05 18:51:15 +0200247 $params['mode'] = strtolower($params['mode']);
248 if ( ! isset($this->_modes['mcrypt'][$params['mode']]))
Andrey Andreev818aedb2014-02-03 11:30:25 +0200249 {
250 log_message('error', 'Encryption: MCrypt mode '.strtotupper($params['mode']).' is not available.');
251 }
252 else
253 {
Andrey Andreevf4017672014-02-05 18:51:15 +0200254 $this->_mode = $this->_modes['mcrypt'][$params['mode']];
Andrey Andreev818aedb2014-02-03 11:30:25 +0200255 }
256 }
257
258 if (isset($this->_cipher, $this->_mode))
259 {
260 if (is_resource($this->_handle)
261 && (strtolower(mcrypt_enc_get_algorithms_name($this->_handle)) !== $this->_cipher
262 OR strtolower(mcrypt_enc_get_modes_name($this->_handle)) !== $this->_mode)
263 )
264 {
265 mcrypt_module_close($this->_handle);
266 }
267
268 if ($this->_handle = mcrypt_module_open($this->_cipher, '', $this->_mode, ''))
269 {
270 log_message('debug', 'Encryption: MCrypt cipher '.strtoupper($this->_cipher).' initialized in '.strtoupper($this->_mode).' mode.');
271 }
272 else
273 {
274 log_message('error', 'Encryption: Unable to initialize MCrypt with cipher '.strtoupper($this->_cipher).' in '.strtoupper($this->_mode).' mode.');
275 }
276 }
277 }
278
279 // --------------------------------------------------------------------
280
281 /**
282 * Initialize OpenSSL
283 *
284 * @param array $params Configuration parameters
285 * @return void
286 */
287 protected function _openssl_initialize($params)
288 {
289 if ( ! empty($params['cipher']))
290 {
291 $params['cipher'] = strtolower($params['cipher']);
292 $this->_cipher_alias($params['cipher']);
293 $this->_cipher = $params['cipher'];
294 }
295
296 if ( ! empty($params['mode']))
297 {
Andrey Andreevf4017672014-02-05 18:51:15 +0200298 $params['mode'] = strtolower($params['mode']);
299 if ( ! isset($this->_modes['openssl'][$params['mode']]))
300 {
301 log_message('error', 'Encryption: OpenSSL mode '.strtotupper($params['mode']).' is not available.');
302 }
303 else
304 {
305 $this->_mode = $this->_modes['openssl'][$params['mode']];
306 }
Andrey Andreev818aedb2014-02-03 11:30:25 +0200307 }
308
309 if (isset($this->_cipher, $this->_mode))
310 {
Andrey Andreevf4017672014-02-05 18:51:15 +0200311 // This is mostly for the stream mode, which doesn't get suffixed in OpenSSL
312 $handle = empty($this->_mode)
Andrey Andreev818aedb2014-02-03 11:30:25 +0200313 ? $this->_cipher
314 : $this->_cipher.'-'.$this->_mode;
315
Andrey Andreev50ccc382014-02-04 23:30:06 +0200316 if ( ! in_array($handle, openssl_get_cipher_methods(), TRUE))
Andrey Andreev818aedb2014-02-03 11:30:25 +0200317 {
318 $this->_handle = NULL;
319 log_message('error', 'Encryption: Unable to initialize OpenSSL with method '.strtoupper($handle).'.');
320 }
321 else
322 {
323 $this->_handle = $handle;
324 log_message('debug', 'Encryption: OpenSSL initialized with method '.strtoupper($handle).'.');
325 }
326 }
327 }
328
329 // --------------------------------------------------------------------
330
331 /**
Andrey Andreev42183de2014-06-22 00:09:36 +0300332 * Create a random key
333 *
334 * @param int $length Output length
335 * @return string
336 */
337 public function create_key($length)
338 {
339 return ($this->_driver === 'mcrypt')
340 ? mcrypt_create_iv($length, MCRYPT_DEV_URANDOM)
341 : openssl_random_pseudo_bytes($length);
342 }
343
344 // --------------------------------------------------------------------
345
346 /**
Andrey Andreev818aedb2014-02-03 11:30:25 +0200347 * Encrypt
348 *
349 * @param string $data Input data
350 * @param array $params Input parameters
351 * @return string
352 */
353 public function encrypt($data, array $params = NULL)
354 {
Andrey Andreev29cade42014-02-04 14:05:58 +0200355 if (($params = $this->_get_params($params)) === FALSE)
Andrey Andreev818aedb2014-02-03 11:30:25 +0200356 {
357 return FALSE;
358 }
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200359
Andrey Andreev2da35502014-07-07 14:41:57 +0300360 isset($params['key']) OR $params['key'] = $this->hkdf($this->_key, 'sha512', NULL, self::strlen($this->_key), 'encryption');
Andrey Andreev818aedb2014-02-03 11:30:25 +0200361
362 if (($data = $this->{'_'.$this->_driver.'_encrypt'}($data, $params)) === FALSE)
363 {
364 return FALSE;
365 }
366
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200367 $params['base64'] && $data = base64_encode($data);
Andrey Andreev29cade42014-02-04 14:05:58 +0200368
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200369 if (isset($params['hmac_digest']))
Andrey Andreev29cade42014-02-04 14:05:58 +0200370 {
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200371 isset($params['hmac_key']) OR $params['hmac_key'] = $this->hkdf($this->_key, 'sha512', NULL, NULL, 'authentication');
372 return hash_hmac($params['hmac_digest'], $data, $params['hmac_key'], ! $params['base64']).$data;
Andrey Andreev29cade42014-02-04 14:05:58 +0200373 }
374
375 return $data;
Andrey Andreev818aedb2014-02-03 11:30:25 +0200376 }
377
378 // --------------------------------------------------------------------
379
380 /**
381 * Encrypt via MCrypt
382 *
383 * @param string $data Input data
384 * @param array $params Input parameters
385 * @return string
386 */
387 protected function _mcrypt_encrypt($data, $params)
388 {
Andrey Andreev29cade42014-02-04 14:05:58 +0200389 if ( ! is_resource($params['handle']))
390 {
391 return FALSE;
392 }
Andrey Andreeve7516b02014-02-05 13:45:31 +0200393
Andrey Andreev1e83d692014-06-19 20:08:59 +0300394 // The greater-than-1 comparison is mostly a work-around for a bug,
395 // where 1 is returned for ARCFour instead of 0.
396 $iv = (($iv_size = mcrypt_enc_get_iv_size($params['handle'])) > 1)
397 ? mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM)
398 : NULL;
399
400 if (mcrypt_generic_init($params['handle'], $params['key'], $iv) < 0)
Andrey Andreev818aedb2014-02-03 11:30:25 +0200401 {
402 if ($params['handle'] !== $this->_handle)
403 {
404 mcrypt_module_close($params['handle']);
405 }
406
407 return FALSE;
408 }
409
410 // Use PKCS#7 padding in order to ensure compatibility with OpenSSL
Andrey Andreevf4017672014-02-05 18:51:15 +0200411 // and other implementations outside of PHP.
412 if (in_array(strtolower(mcrypt_enc_get_modes_name($params['handle'])), array('cbc', 'ecb'), TRUE))
413 {
414 $block_size = mcrypt_enc_get_block_size($params['handle']);
Andrey Andreev2da35502014-07-07 14:41:57 +0300415 $pad = $block_size - (self::strlen($data) % $block_size);
Andrey Andreevf4017672014-02-05 18:51:15 +0200416 $data .= str_repeat(chr($pad), $pad);
417 }
Andrey Andreev818aedb2014-02-03 11:30:25 +0200418
Andrey Andreeve7516b02014-02-05 13:45:31 +0200419 // Work-around for yet another strange behavior in MCrypt.
420 //
421 // When encrypting in ECB mode, the IV is ignored. Yet
422 // mcrypt_enc_get_iv_size() returns a value larger than 0
423 // even if ECB is used AND mcrypt_generic_init() complains
424 // if you don't pass an IV with length equal to the said
425 // return value.
426 //
427 // This probably would've been fine (even though still wasteful),
428 // but OpenSSL isn't that dumb and we need to make the process
429 // portable, so ...
430 $data = (mcrypt_enc_get_modes_name($params['handle']) !== 'ECB')
Andrey Andreev1e83d692014-06-19 20:08:59 +0300431 ? $iv.mcrypt_generic($params['handle'], $data)
Andrey Andreeve7516b02014-02-05 13:45:31 +0200432 : mcrypt_generic($params['handle'], $data);
Andrey Andreev818aedb2014-02-03 11:30:25 +0200433
434 mcrypt_generic_deinit($params['handle']);
435 if ($params['handle'] !== $this->_handle)
436 {
Andrey Andreev50ccc382014-02-04 23:30:06 +0200437 mcrypt_module_close($params['handle']);
Andrey Andreev818aedb2014-02-03 11:30:25 +0200438 }
439
440 return $data;
441 }
442
443 // --------------------------------------------------------------------
444
445 /**
446 * Encrypt via OpenSSL
447 *
448 * @param string $data Input data
449 * @param array $params Input parameters
450 * @return string
451 */
452 protected function _openssl_encrypt($data, $params)
453 {
Andrey Andreev29cade42014-02-04 14:05:58 +0200454 if (empty($params['handle']))
455 {
456 return FALSE;
457 }
Andrey Andreev1e83d692014-06-19 20:08:59 +0300458
459 $iv = ($iv_size = openssl_cipher_iv_length($params['handle']))
460 ? openssl_random_pseudo_bytes($iv_size)
461 : NULL;
Andrey Andreev29cade42014-02-04 14:05:58 +0200462
Andrey Andreev818aedb2014-02-03 11:30:25 +0200463 $data = openssl_encrypt(
464 $data,
465 $params['handle'],
466 $params['key'],
467 1, // DO NOT TOUCH!
Andrey Andreev1e83d692014-06-19 20:08:59 +0300468 $iv
Andrey Andreev818aedb2014-02-03 11:30:25 +0200469 );
470
471 if ($data === FALSE)
472 {
473 return FALSE;
474 }
475
Andrey Andreev1e83d692014-06-19 20:08:59 +0300476 return $iv.$data;
Andrey Andreev818aedb2014-02-03 11:30:25 +0200477 }
478
479 // --------------------------------------------------------------------
480
481 /**
482 * Decrypt
483 *
484 * @param string $data Encrypted data
485 * @param array $params Input parameters
486 * @return string
487 */
488 public function decrypt($data, array $params = NULL)
489 {
Andrey Andreev29cade42014-02-04 14:05:58 +0200490 if (($params = $this->_get_params($params)) === FALSE)
Andrey Andreev818aedb2014-02-03 11:30:25 +0200491 {
492 return FALSE;
493 }
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200494
495 if (isset($params['hmac_digest']))
496 {
Andrey Andreev29cade42014-02-04 14:05:58 +0200497 // This might look illogical, but it is done during encryption as well ...
Andrey Andreev177144f2014-02-04 18:07:34 +0200498 // The 'base64' value is effectively an inverted "raw data" parameter
Andrey Andreev29cade42014-02-04 14:05:58 +0200499 $digest_size = ($params['base64'])
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200500 ? $this->_digests[$params['hmac_digest']] * 2
501 : $this->_digests[$params['hmac_digest']];
Andrey Andreev7c554482014-02-06 02:38:27 +0200502
Andrey Andreev2da35502014-07-07 14:41:57 +0300503 if (self::strlen($data) <= $digest_size)
Andrey Andreev7c554482014-02-06 02:38:27 +0200504 {
505 return FALSE;
506 }
507
Andrey Andreev9fa275e2014-07-07 14:43:51 +0300508 $hmac_input = self::substr($data, 0, $digest_size);
509 $data = self::substr($data, $digest_size);
Andrey Andreev29cade42014-02-04 14:05:58 +0200510
Andrey Andreev7c554482014-02-06 02:38:27 +0200511 isset($params['hmac_key']) OR $params['hmac_key'] = $this->hkdf($this->_key, 'sha512', NULL, NULL, 'authentication');
512 $hmac_check = hash_hmac($params['hmac_digest'], $data, $params['hmac_key'], ! $params['base64']);
513
514 // Time-attack-safe comparison
515 $diff = 0;
516 for ($i = 0; $i < $digest_size; $i++)
517 {
518 $diff |= ord($hmac_input[$i]) ^ ord($hmac_check[$i]);
519 }
520
521 if ($diff !== 0)
Andrey Andreev29cade42014-02-04 14:05:58 +0200522 {
523 return FALSE;
524 }
525 }
526
527 if ($params['base64'])
Andrey Andreev818aedb2014-02-03 11:30:25 +0200528 {
529 $data = base64_decode($data);
530 }
531
Andrey Andreev2da35502014-07-07 14:41:57 +0300532 isset($params['key']) OR $params['key'] = $this->hkdf($this->_key, 'sha512', NULL, self::strlen($this->_key), 'encryption');
Andrey Andreev81e10642014-02-07 01:43:36 +0200533
Andrey Andreev818aedb2014-02-03 11:30:25 +0200534 return $this->{'_'.$this->_driver.'_decrypt'}($data, $params);
535 }
536
537 // --------------------------------------------------------------------
538
539 /**
540 * Decrypt via MCrypt
541 *
542 * @param string $data Encrypted data
543 * @param array $params Input parameters
544 * @return string
545 */
546 protected function _mcrypt_decrypt($data, $params)
547 {
Andrey Andreev29cade42014-02-04 14:05:58 +0200548 if ( ! is_resource($params['handle']))
549 {
550 return FALSE;
551 }
Andrey Andreev1e83d692014-06-19 20:08:59 +0300552
553 // The greater-than-1 comparison is mostly a work-around for a bug,
554 // where 1 is returned for ARCFour instead of 0.
555 if (($iv_size = mcrypt_enc_get_iv_size($params['handle'])) > 1)
Andrey Andreeve7516b02014-02-05 13:45:31 +0200556 {
Andrey Andreev1e83d692014-06-19 20:08:59 +0300557 if (mcrypt_enc_get_modes_name($params['handle']) !== 'ECB')
Andrey Andreeve7516b02014-02-05 13:45:31 +0200558 {
Andrey Andreev9fa275e2014-07-07 14:43:51 +0300559 $iv = self::substr($data, 0, $iv_size);
560 $data = self::substr($data, $iv_size);
Andrey Andreeve7516b02014-02-05 13:45:31 +0200561 }
562 else
563 {
Andrey Andreev1e83d692014-06-19 20:08:59 +0300564 // MCrypt is dumb and this is ignored, only size matters
565 $iv = str_repeat("\x0", $iv_size);
Andrey Andreeve7516b02014-02-05 13:45:31 +0200566 }
567 }
Andrey Andreev1e83d692014-06-19 20:08:59 +0300568 else
569 {
570 $iv = NULL;
571 }
Andrey Andreeve7516b02014-02-05 13:45:31 +0200572
Andrey Andreev1e83d692014-06-19 20:08:59 +0300573 if (mcrypt_generic_init($params['handle'], $params['key'], $iv) < 0)
Andrey Andreev818aedb2014-02-03 11:30:25 +0200574 {
575 if ($params['handle'] !== $this->_handle)
576 {
577 mcrypt_module_close($params['handle']);
578 }
579
580 return FALSE;
581 }
582
583 $data = mdecrypt_generic($params['handle'], $data);
Andrey Andreevf4017672014-02-05 18:51:15 +0200584 // Remove PKCS#7 padding, if necessary
585 if (in_array(strtolower(mcrypt_enc_get_modes_name($params['handle'])), array('cbc', 'ecb'), TRUE))
586 {
Andrey Andreev9fa275e2014-07-07 14:43:51 +0300587 $data = self::substr($data, 0, -ord($data[self::strlen($data)-1]));
Andrey Andreevf4017672014-02-05 18:51:15 +0200588 }
Andrey Andreev818aedb2014-02-03 11:30:25 +0200589
590 mcrypt_generic_deinit($params['handle']);
591 if ($params['handle'] !== $this->_handle)
592 {
Andrey Andreev50ccc382014-02-04 23:30:06 +0200593 mcrypt_module_close($params['handle']);
Andrey Andreev818aedb2014-02-03 11:30:25 +0200594 }
595
Andrey Andreevf4017672014-02-05 18:51:15 +0200596 return $data;
Andrey Andreev818aedb2014-02-03 11:30:25 +0200597 }
598
599 // --------------------------------------------------------------------
600
601 /**
602 * Decrypt via OpenSSL
603 *
604 * @param string $data Encrypted data
605 * @param array $params Input parameters
606 * @return string
607 */
608 protected function _openssl_decrypt($data, $params)
609 {
Andrey Andreev1e83d692014-06-19 20:08:59 +0300610 if ($iv_size = openssl_cipher_iv_length($params['handle']))
Andrey Andreeve7516b02014-02-05 13:45:31 +0200611 {
Andrey Andreev9fa275e2014-07-07 14:43:51 +0300612 $iv = self::substr($data, 0, $iv_size);
613 $data = self::substr($data, $iv_size);
Andrey Andreev1e83d692014-06-19 20:08:59 +0300614 }
615 else
616 {
617 $iv = NULL;
Andrey Andreeve7516b02014-02-05 13:45:31 +0200618 }
619
Andrey Andreev29cade42014-02-04 14:05:58 +0200620 return empty($params['handle'])
621 ? FALSE
622 : openssl_decrypt(
623 $data,
624 $params['handle'],
625 $params['key'],
626 1, // DO NOT TOUCH!
Andrey Andreev1e83d692014-06-19 20:08:59 +0300627 $iv
Andrey Andreev29cade42014-02-04 14:05:58 +0200628 );
Andrey Andreev818aedb2014-02-03 11:30:25 +0200629 }
630
631 // --------------------------------------------------------------------
632
633 /**
Andrey Andreev29cade42014-02-04 14:05:58 +0200634 * Get params
Andrey Andreev818aedb2014-02-03 11:30:25 +0200635 *
636 * @param array $params Input parameters
637 * @return array
638 */
Andrey Andreev29cade42014-02-04 14:05:58 +0200639 protected function _get_params($params)
Andrey Andreev818aedb2014-02-03 11:30:25 +0200640 {
641 if (empty($params))
642 {
Andrey Andreev50ccc382014-02-04 23:30:06 +0200643 return isset($this->_cipher, $this->_mode, $this->_key, $this->_handle)
Andrey Andreev29cade42014-02-04 14:05:58 +0200644 ? array(
645 'handle' => $this->_handle,
646 'cipher' => $this->_cipher,
647 'mode' => $this->_mode,
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200648 'key' => NULL,
Andrey Andreev29cade42014-02-04 14:05:58 +0200649 'base64' => TRUE,
Andrey Andreevab9971f2014-07-02 19:09:08 +0300650 'hmac_digest' => 'sha512',
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200651 'hmac_key' => NULL
Andrey Andreev29cade42014-02-04 14:05:58 +0200652 )
653 : FALSE;
654 }
655 elseif ( ! isset($params['cipher'], $params['mode'], $params['key']))
656 {
657 return FALSE;
658 }
659
Andrey Andreevf4017672014-02-05 18:51:15 +0200660 if (isset($params['mode']))
661 {
662 $params['mode'] = strtolower($params['mode']);
663 if ( ! isset($this->_modes[$this->_driver][$params['mode']]))
664 {
665 return FALSE;
666 }
667 else
668 {
669 $params['mode'] = $this->_modes[$this->_driver][$params['mode']];
670 }
671 }
672
Andrey Andreevab9971f2014-07-02 19:09:08 +0300673 if (isset($params['hmac']) && $params['hmac'] === FALSE)
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200674 {
675 $params['hmac_digest'] = $params['hmac_key'] = NULL;
676 }
677 else
678 {
679 if ( ! isset($params['hmac_key']))
680 {
681 return FALSE;
682 }
683 elseif (isset($params['hmac_digest']))
684 {
685 $params['hmac_digest'] = strtolower($params['hmac_digest']);
686 if ( ! isset($this->_digests[$params['hmac_digest']]))
687 {
688 return FALSE;
689 }
690 }
691 else
692 {
693 $params['hmac_digest'] = 'sha512';
694 }
695 }
696
Andrey Andreev818aedb2014-02-03 11:30:25 +0200697 $params = array(
698 'handle' => NULL,
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200699 'cipher' => $params['cipher'],
700 'mode' => $params['mode'],
701 'key' => $params['key'],
Andrey Andreev4b450652014-02-10 06:59:54 +0200702 'base64' => isset($params['raw_data']) ? ! $params['raw_data'] : FALSE,
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200703 'hmac_digest' => $params['hmac_digest'],
704 'hmac_key' => $params['hmac_key']
Andrey Andreev818aedb2014-02-03 11:30:25 +0200705 );
706
Andrey Andreev818aedb2014-02-03 11:30:25 +0200707 $this->_cipher_alias($params['cipher']);
Andrey Andreev29cade42014-02-04 14:05:58 +0200708 $params['handle'] = ($params['cipher'] !== $this->_cipher OR $params['mode'] !== $this->_mode)
709 ? $this->{'_'.$this->_driver.'_get_handle'}($params['cipher'], $params['mode'])
710 : $this->_handle;
Andrey Andreev818aedb2014-02-03 11:30:25 +0200711
712 return $params;
713 }
714
715 // --------------------------------------------------------------------
716
717 /**
Andrey Andreev29cade42014-02-04 14:05:58 +0200718 * Get MCrypt handle
Andrey Andreev818aedb2014-02-03 11:30:25 +0200719 *
Andrey Andreev29cade42014-02-04 14:05:58 +0200720 * @param string $cipher Cipher name
721 * @param string $mode Encryption mode
722 * @return resource
Andrey Andreev818aedb2014-02-03 11:30:25 +0200723 */
Andrey Andreev29cade42014-02-04 14:05:58 +0200724 protected function _mcrypt_get_handle($cipher, $mode)
Andrey Andreev818aedb2014-02-03 11:30:25 +0200725 {
Andrey Andreev29cade42014-02-04 14:05:58 +0200726 return mcrypt_module_open($cipher, '', $mode, '');
727 }
Andrey Andreev818aedb2014-02-03 11:30:25 +0200728
Andrey Andreev29cade42014-02-04 14:05:58 +0200729 // --------------------------------------------------------------------
Andrey Andreev818aedb2014-02-03 11:30:25 +0200730
Andrey Andreev29cade42014-02-04 14:05:58 +0200731 /**
732 * Get OpenSSL handle
733 *
734 * @param string $cipher Cipher name
735 * @param string $mode Encryption mode
736 * @return string
737 */
738 protected function _openssl_get_handle($cipher, $mode)
739 {
740 // OpenSSL methods aren't suffixed with '-stream' for this mode
741 return ($mode === 'stream')
742 ? $cipher
743 : $cipher.'-'.$mode;
Andrey Andreev818aedb2014-02-03 11:30:25 +0200744 }
745
746 // --------------------------------------------------------------------
747
748 /**
749 * Cipher alias
750 *
751 * Tries to translate cipher names between MCrypt and OpenSSL's "dialects".
752 *
753 * @param string $cipher Cipher name
754 * @return void
755 */
756 protected function _cipher_alias(&$cipher)
757 {
758 static $dictionary;
759
760 if (empty($dictionary))
761 {
762 $dictionary = array(
763 'mcrypt' => array(
Andrey Andreev50ccc382014-02-04 23:30:06 +0200764 'aes-128' => 'rijndael-128',
765 'aes-192' => 'rijndael-128',
766 'aes-256' => 'rijndael-128',
Andrey Andreevd9a48da2014-02-05 14:10:28 +0200767 'des3-ede3' => 'tripledes',
768 'bf' => 'blowfish',
Andrey Andreeve8088d62014-02-06 05:01:48 +0200769 'cast5' => 'cast-128',
770 'rc4' => 'arcfour',
771 'rc4-40' => 'arcfour'
Andrey Andreev818aedb2014-02-03 11:30:25 +0200772 ),
773 'openssl' => array(
Andrey Andreev50ccc382014-02-04 23:30:06 +0200774 'rijndael-128' => 'aes-128',
Andrey Andreevd9a48da2014-02-05 14:10:28 +0200775 'tripledes' => 'des-ede3',
Andrey Andreeve8088d62014-02-06 05:01:48 +0200776 'blowfish' => 'bf',
777 'cast-128' => 'cast5',
778 'arcfour' => 'rc4-40',
779 'rc4' => 'rc4-40'
Andrey Andreev818aedb2014-02-03 11:30:25 +0200780 )
781 );
782
Andrey Andreevd9a48da2014-02-05 14:10:28 +0200783 // Notes:
784 //
Andrey Andreeve8088d62014-02-06 05:01:48 +0200785 // - Rijndael-128 is, at the same time all three of AES-128,
786 // AES-192 and AES-256. The only difference between them is
787 // the key size. Rijndael-192, Rijndael-256 on the other hand
788 // also have different block sizes and are NOT AES-compatible.
789 //
Andrey Andreevd9a48da2014-02-05 14:10:28 +0200790 // - Blowfish is said to be supporting key sizes between
791 // 4 and 56 bytes, but it appears that between MCrypt and
792 // OpenSSL, only those of 16 and more bytes are compatible.
Andrey Andreeve8088d62014-02-06 05:01:48 +0200793 // Also, don't know what MCrypt's 'blowfish-compat' is.
794 //
795 // - CAST-128/CAST5 produces a longer cipher when encrypted via
796 // OpenSSL, but (strangely enough) can be decrypted by either
797 // extension anyway.
Andrey Andreev18767e32014-03-04 22:21:35 +0200798 // Also, it appears that OpenSSL uses 16 rounds regardless of
799 // the key size, while RFC2144 says that for key sizes lower
800 // than 11 bytes, only 12 rounds should be used. This makes
801 // it portable only with keys of between 11 and 16 bytes.
Andrey Andreeve8088d62014-02-06 05:01:48 +0200802 //
803 // - RC4 (ARCFour) has a strange implementation under OpenSSL.
804 // Its 'rc4-40' cipher method seems to work flawlessly, yet
805 // there's another one, 'rc4' that only works with a 16-byte key.
806 //
807 // - DES is compatible, but doesn't need an alias.
Andrey Andreevd9a48da2014-02-05 14:10:28 +0200808 //
809 // Other seemingly matching ciphers between MCrypt, OpenSSL:
Andrey Andreev818aedb2014-02-03 11:30:25 +0200810 //
Andrey Andreeve8088d62014-02-06 05:01:48 +0200811 // - RC2 is NOT compatible and only an obscure forum post
812 // confirms that it is MCrypt's fault.
Andrey Andreev818aedb2014-02-03 11:30:25 +0200813 }
814
Andrey Andreev50ccc382014-02-04 23:30:06 +0200815 if (isset($dictionary[$this->_driver][$cipher]))
Andrey Andreev818aedb2014-02-03 11:30:25 +0200816 {
Andrey Andreev50ccc382014-02-04 23:30:06 +0200817 $cipher = $dictionary[$this->_driver][$cipher];
Andrey Andreev818aedb2014-02-03 11:30:25 +0200818 }
819 }
820
821 // --------------------------------------------------------------------
822
823 /**
Andrey Andreev29cade42014-02-04 14:05:58 +0200824 * HKDF
825 *
826 * @link https://tools.ietf.org/rfc/rfc5869.txt
827 * @param $key Input key
828 * @param $digest A SHA-2 hashing algorithm
829 * @param $salt Optional salt
Andrey Andreev29cade42014-02-04 14:05:58 +0200830 * @param $length Output length (defaults to the selected digest size)
Andrey Andreev4b450652014-02-10 06:59:54 +0200831 * @param $info Optional context/application-specific info
Andrey Andreev29cade42014-02-04 14:05:58 +0200832 * @return string A pseudo-random key
833 */
834 public function hkdf($key, $digest = 'sha512', $salt = NULL, $length = NULL, $info = '')
835 {
836 if ( ! isset($this->_digests[$digest]))
837 {
838 return FALSE;
839 }
840
841 if (empty($length) OR ! is_int($length))
842 {
843 $length = $this->_digests[$digest];
844 }
845 elseif ($length > (255 * $this->_digests[$digest]))
846 {
847 return FALSE;
848 }
849
Andrey Andreev2da35502014-07-07 14:41:57 +0300850 self::strlen($salt) OR $salt = str_repeat("\0", $this->_digests[$digest]);
Andrey Andreev29cade42014-02-04 14:05:58 +0200851
852 $prk = hash_hmac($digest, $key, $salt, TRUE);
853 $key = '';
Andrey Andreev2da35502014-07-07 14:41:57 +0300854 for ($key_block = '', $block_index = 1; self::strlen($key) < $length; $block_index++)
Andrey Andreev29cade42014-02-04 14:05:58 +0200855 {
856 $key_block = hash_hmac($digest, $key_block.$info.chr($block_index), $prk, TRUE);
857 $key .= $key_block;
858 }
859
Andrey Andreev9fa275e2014-07-07 14:43:51 +0300860 return self::substr($key, 0, $length);
Andrey Andreev29cade42014-02-04 14:05:58 +0200861 }
862
863 // --------------------------------------------------------------------
864
865 /**
Andrey Andreev818aedb2014-02-03 11:30:25 +0200866 * __get() magic
867 *
868 * @param string $key Property name
869 * @return mixed
870 */
871 public function __get($key)
872 {
Andrey Andreev81e10642014-02-07 01:43:36 +0200873 // Because aliases
874 if ($key === 'mode')
875 {
876 return array_search($this->_mode, $this->_modes[$this->_driver], TRUE);
877 }
878 elseif (in_array($key, array('cipher', 'driver', 'drivers', 'digests'), TRUE))
879 {
880 return $this->{'_'.$key};
881 }
882
883 return NULL;
Andrey Andreev818aedb2014-02-03 11:30:25 +0200884 }
885
Andrey Andreev2da35502014-07-07 14:41:57 +0300886 // --------------------------------------------------------------------
887
888 /**
889 * Byte-safe strlen()
890 *
891 * @param string $str
892 * @return integer
893 */
894 protected static function strlen($str)
895 {
896 return (self::$func_override)
897 ? mb_strlen($str, '8bit')
898 : strlen($str);
899 }
900
901 // --------------------------------------------------------------------
902
903 /**
904 * Byte-safe substr()
905 *
906 * @param string $str
907 * @param int $start
908 * @param int $length
909 * @return string
910 */
Andrey Andreev35a7b442014-07-12 21:46:26 +0300911 protected static function substr($str, $start, $length = NULL)
Andrey Andreev2da35502014-07-07 14:41:57 +0300912 {
913 if (self::$func_override)
914 {
Andrey Andreev35a7b442014-07-12 21:46:26 +0300915 // mb_substr($str, $start, null, '8bit') returns an empty
916 // string on PHP 5.3
917 isset($length) OR $length = ($start >= 0 ? self::strlen($str) - $start : -$start);
Andrey Andreev11beac22014-07-12 18:28:38 +0300918 return mb_substr($str, $start, $length, '8bit');
Andrey Andreev2da35502014-07-07 14:41:57 +0300919 }
920
921 return isset($length)
922 ? substr($str, $start, $length)
923 : substr($str, $start);
924 }
Andrey Andreev818aedb2014-02-03 11:30:25 +0200925}
926
927/* End of file Encryption.php */
928/* Location: ./system/libraries/Encryption.php */