blob: 3a5409839cb83210b2bc12ad2d98099341441192 [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 *
7 * NOTICE OF LICENSE
8 *
9 * Licensed under the Open Software License version 3.0
10 *
11 * This source file is subject to the Open Software License (OSL 3.0) that is
12 * bundled with this package in the files license.txt / license.rst. It is
13 * also available through the world wide web at this URL:
14 * http://opensource.org/licenses/OSL-3.0
15 * If you did not receive a copy of the license and are unable to obtain it
16 * through the world wide web, please send an email to
17 * licensing@ellislab.com so we can send you a copy immediately.
18 *
19 * @package CodeIgniter
20 * @author EllisLab Dev Team
21 * @copyright Copyright (c) 2008 - 2013, EllisLab, Inc. (http://ellislab.com/)
22 * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
23 * @link http://codeigniter.com
24 * @since Version 3.0
25 * @filesource
26 */
27defined('BASEPATH') OR exit('No direct script access allowed');
28
29/**
30 * CodeIgniter Encryption Class
31 *
32 * Provides two-way keyed encryption via PHP's MCrypt and/or OpenSSL extensions.
33 *
34 * @package CodeIgniter
35 * @subpackage Libraries
36 * @category Libraries
37 * @author Andrey Andreev
38 * @link http://codeigniter.com/user_guide/libraries/encryption.html
39 */
40class CI_Encryption {
41
42 /**
43 * Encryption cipher
44 *
45 * @var string
46 */
Andrey Andreev81e10642014-02-07 01:43:36 +020047 protected $_cipher = 'aes-128';
Andrey Andreev818aedb2014-02-03 11:30:25 +020048
49 /**
50 * Cipher mode
51 *
52 * @var string
53 */
54 protected $_mode = 'cbc';
55
56 /**
57 * Cipher handle
58 *
59 * @var mixed
60 */
61 protected $_handle;
62
63 /**
64 * Encryption key
65 *
66 * @var string
67 */
68 protected $_key;
69
70 /**
71 * PHP extension to be used
72 *
73 * @var string
74 */
75 protected $_driver;
76
77 /**
78 * List of usable drivers (PHP extensions)
79 *
80 * @var array
81 */
82 protected $_drivers = array();
83
Andrey Andreev29cade42014-02-04 14:05:58 +020084 /**
Andrey Andreevf4017672014-02-05 18:51:15 +020085 * List of available modes
86 *
87 * @var array
88 */
89 protected $_modes = array(
90 'mcrypt' => array(
91 'cbc' => 'cbc',
92 'ecb' => 'ecb',
93 'ofb' => 'nofb',
94 'ofb8' => 'ofb',
95 'cfb' => 'ncfb',
96 'cfb8' => 'cfb',
97 'ctr' => 'ctr',
98 'stream' => 'stream'
99 ),
100 'openssl' => array(
101 'cbc' => 'cbc',
102 'ecb' => 'ecb',
103 'ofb' => 'ofb',
104 'cfb' => 'cfb',
105 'cfb8' => 'cfb8',
106 'ctr' => 'ctr',
107 'stream' => '',
108 'gcm' => 'gcm',
109 'xts' => 'xts'
110 )
111 );
112
113 /**
Andrey Andreev29cade42014-02-04 14:05:58 +0200114 * List of supported HMAC algorightms
115 *
116 * name => digest size pairs
117 *
118 * @var array
119 */
120 protected $_digests = array(
121 'sha224' => 28,
122 'sha256' => 32,
123 'sha384' => 48,
124 'sha512' => 64
125 );
126
Andrey Andreev818aedb2014-02-03 11:30:25 +0200127 // --------------------------------------------------------------------
128
129 /**
130 * Class constructor
131 *
132 * @param array $params Configuration parameters
133 * @return void
134 */
135 public function __construct(array $params = array())
136 {
137 $this->_drivers = array(
Andrey Andreev8e202162014-02-05 18:59:55 +0200138 'mcrypt' => defined('MCRYPT_DEV_URANDOM'),
Andrey Andreev818aedb2014-02-03 11:30:25 +0200139 // While OpenSSL is available for PHP 5.3.0, an IV parameter
140 // for the encrypt/decrypt functions is only available since 5.3.3
141 'openssl' => (is_php('5.3.3') && extension_loaded('openssl'))
142 );
143
144 if ( ! $this->_drivers['mcrypt'] && ! $this->_drivers['openssl'])
145 {
146 return show_error('Encryption: Unable to find an available encryption driver.');
147 }
148
149 $this->initialize($params);
Andrey Andreev81e10642014-02-07 01:43:36 +0200150 if ( ! isset($this->_key) && strlen($key = config_item('encryption_key')) > 0)
Andrey Andreev818aedb2014-02-03 11:30:25 +0200151 {
Andrey Andreev81e10642014-02-07 01:43:36 +0200152 $this->_key = $key;
Andrey Andreev818aedb2014-02-03 11:30:25 +0200153 }
154
155 log_message('debug', 'Encryption Class Initialized');
156 }
157
158 // --------------------------------------------------------------------
159
160 /**
161 * Initialize
162 *
163 * @param array $params Configuration parameters
164 * @return CI_Encryption
165 */
166 public function initialize(array $params)
167 {
168 if ( ! empty($params['driver']))
169 {
170 if (isset($this->_drivers[$params['driver']]))
171 {
Andrey Andreev50ccc382014-02-04 23:30:06 +0200172 if ($this->_drivers[$params['driver']])
Andrey Andreev818aedb2014-02-03 11:30:25 +0200173 {
174 $this->_driver = $params['driver'];
175 }
176 else
177 {
178 log_message('error', "Encryption: Driver '".$params['driver']."' is not available.");
179 }
180 }
181 else
182 {
183 log_message('error', "Encryption: Unknown driver '".$params['driver']."' cannot be configured.");
184 }
185 }
186
Andrey Andreev912831f2014-02-04 17:21:37 +0200187 if (empty($this->_driver))
188 {
Andrey Andreev8e202162014-02-05 18:59:55 +0200189 $this->_driver = ($this->_drivers['openssl'] === TRUE)
190 ? 'openssl'
191 : 'mcrypt';
Andrey Andreev912831f2014-02-04 17:21:37 +0200192
193 log_message('debug', "Encryption: Auto-configured driver '".$this->_driver."'.");
194 }
195
Andrey Andreev818aedb2014-02-03 11:30:25 +0200196 empty($params['key']) OR $this->_key = $params['key'];
197 $this->{'_'.$this->_driver.'_initialize'}($params);
198 return $this;
199 }
200
201 // --------------------------------------------------------------------
202
203 /**
204 * Initialize MCrypt
205 *
206 * @param array $params Configuration parameters
207 * @return void
208 */
209 protected function _mcrypt_initialize($params)
210 {
211 if ( ! empty($params['cipher']))
212 {
213 $params['cipher'] = strtolower($params['cipher']);
214 $this->_cipher_alias($params['cipher']);
215
216 if ( ! in_array($params['cipher'], mcrypt_list_algorithms(), TRUE))
217 {
218 log_message('error', 'Encryption: MCrypt cipher '.strtoupper($params['cipher']).' is not available.');
219 }
220 else
221 {
222 $this->_cipher = $params['cipher'];
223 }
224 }
225
226 if ( ! empty($params['mode']))
227 {
Andrey Andreevf4017672014-02-05 18:51:15 +0200228 $params['mode'] = strtolower($params['mode']);
229 if ( ! isset($this->_modes['mcrypt'][$params['mode']]))
Andrey Andreev818aedb2014-02-03 11:30:25 +0200230 {
231 log_message('error', 'Encryption: MCrypt mode '.strtotupper($params['mode']).' is not available.');
232 }
233 else
234 {
Andrey Andreevf4017672014-02-05 18:51:15 +0200235 $this->_mode = $this->_modes['mcrypt'][$params['mode']];
Andrey Andreev818aedb2014-02-03 11:30:25 +0200236 }
237 }
238
239 if (isset($this->_cipher, $this->_mode))
240 {
241 if (is_resource($this->_handle)
242 && (strtolower(mcrypt_enc_get_algorithms_name($this->_handle)) !== $this->_cipher
243 OR strtolower(mcrypt_enc_get_modes_name($this->_handle)) !== $this->_mode)
244 )
245 {
246 mcrypt_module_close($this->_handle);
247 }
248
249 if ($this->_handle = mcrypt_module_open($this->_cipher, '', $this->_mode, ''))
250 {
251 log_message('debug', 'Encryption: MCrypt cipher '.strtoupper($this->_cipher).' initialized in '.strtoupper($this->_mode).' mode.');
252 }
253 else
254 {
255 log_message('error', 'Encryption: Unable to initialize MCrypt with cipher '.strtoupper($this->_cipher).' in '.strtoupper($this->_mode).' mode.');
256 }
257 }
258 }
259
260 // --------------------------------------------------------------------
261
262 /**
263 * Initialize OpenSSL
264 *
265 * @param array $params Configuration parameters
266 * @return void
267 */
268 protected function _openssl_initialize($params)
269 {
270 if ( ! empty($params['cipher']))
271 {
272 $params['cipher'] = strtolower($params['cipher']);
273 $this->_cipher_alias($params['cipher']);
274 $this->_cipher = $params['cipher'];
275 }
276
277 if ( ! empty($params['mode']))
278 {
Andrey Andreevf4017672014-02-05 18:51:15 +0200279 $params['mode'] = strtolower($params['mode']);
280 if ( ! isset($this->_modes['openssl'][$params['mode']]))
281 {
282 log_message('error', 'Encryption: OpenSSL mode '.strtotupper($params['mode']).' is not available.');
283 }
284 else
285 {
286 $this->_mode = $this->_modes['openssl'][$params['mode']];
287 }
Andrey Andreev818aedb2014-02-03 11:30:25 +0200288 }
289
290 if (isset($this->_cipher, $this->_mode))
291 {
Andrey Andreevf4017672014-02-05 18:51:15 +0200292 // This is mostly for the stream mode, which doesn't get suffixed in OpenSSL
293 $handle = empty($this->_mode)
Andrey Andreev818aedb2014-02-03 11:30:25 +0200294 ? $this->_cipher
295 : $this->_cipher.'-'.$this->_mode;
296
Andrey Andreev50ccc382014-02-04 23:30:06 +0200297 if ( ! in_array($handle, openssl_get_cipher_methods(), TRUE))
Andrey Andreev818aedb2014-02-03 11:30:25 +0200298 {
299 $this->_handle = NULL;
300 log_message('error', 'Encryption: Unable to initialize OpenSSL with method '.strtoupper($handle).'.');
301 }
302 else
303 {
304 $this->_handle = $handle;
305 log_message('debug', 'Encryption: OpenSSL initialized with method '.strtoupper($handle).'.');
306 }
307 }
308 }
309
310 // --------------------------------------------------------------------
311
312 /**
313 * Encrypt
314 *
315 * @param string $data Input data
316 * @param array $params Input parameters
317 * @return string
318 */
319 public function encrypt($data, array $params = NULL)
320 {
Andrey Andreev29cade42014-02-04 14:05:58 +0200321 if (($params = $this->_get_params($params)) === FALSE)
Andrey Andreev818aedb2014-02-03 11:30:25 +0200322 {
323 return FALSE;
324 }
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200325
Andrey Andreev81e10642014-02-07 01:43:36 +0200326 isset($params['key']) OR $params['key'] = $this->hkdf($this->_key, 'sha512', NULL, strlen($this->_key), 'encryption');
Andrey Andreev818aedb2014-02-03 11:30:25 +0200327
328 if (($data = $this->{'_'.$this->_driver.'_encrypt'}($data, $params)) === FALSE)
329 {
330 return FALSE;
331 }
332
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200333 $params['base64'] && $data = base64_encode($data);
Andrey Andreev29cade42014-02-04 14:05:58 +0200334
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200335 if (isset($params['hmac_digest']))
Andrey Andreev29cade42014-02-04 14:05:58 +0200336 {
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200337 isset($params['hmac_key']) OR $params['hmac_key'] = $this->hkdf($this->_key, 'sha512', NULL, NULL, 'authentication');
338 return hash_hmac($params['hmac_digest'], $data, $params['hmac_key'], ! $params['base64']).$data;
Andrey Andreev29cade42014-02-04 14:05:58 +0200339 }
340
341 return $data;
Andrey Andreev818aedb2014-02-03 11:30:25 +0200342 }
343
344 // --------------------------------------------------------------------
345
346 /**
347 * Encrypt via MCrypt
348 *
349 * @param string $data Input data
350 * @param array $params Input parameters
351 * @return string
352 */
353 protected function _mcrypt_encrypt($data, $params)
354 {
Andrey Andreev29cade42014-02-04 14:05:58 +0200355 if ( ! is_resource($params['handle']))
356 {
357 return FALSE;
358 }
Andrey Andreeve7516b02014-02-05 13:45:31 +0200359 elseif ( ! isset($params['iv']))
360 {
Andrey Andreeve8088d62014-02-06 05:01:48 +0200361 // The greater-than-1 comparison is mostly a work-around for a bug,
362 // where 1 is returned for ARCFour instead of 0.
363 $params['iv'] = (($iv_size = mcrypt_enc_get_iv_size($params['handle'])) > 1)
Andrey Andreev8e202162014-02-05 18:59:55 +0200364 ? mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM)
Andrey Andreeve7516b02014-02-05 13:45:31 +0200365 : NULL;
366 }
367
Andrey Andreeve8088d62014-02-06 05:01:48 +0200368 // CAST-128 compatibility (http://tools.ietf.org/rfc/rfc2144.txt)
369 //
370 // RFC2144 says that keys shorter than 16 bytes are to be padded with
371 // zero bytes to 16 bytes, but (surprise) MCrypt doesn't do that.
372 if ($params['cipher'] === 'cast-128' && ($kl = strlen($params['key'])) < 16)
373 {
374 $params['key'] .= str_repeat("\x0", 16 - $kl);
375 }
Andrey Andreeve7516b02014-02-05 13:45:31 +0200376
377 if (mcrypt_generic_init($params['handle'], $params['key'], $params['iv']) < 0)
Andrey Andreev818aedb2014-02-03 11:30:25 +0200378 {
379 if ($params['handle'] !== $this->_handle)
380 {
381 mcrypt_module_close($params['handle']);
382 }
383
384 return FALSE;
385 }
386
387 // Use PKCS#7 padding in order to ensure compatibility with OpenSSL
Andrey Andreevf4017672014-02-05 18:51:15 +0200388 // and other implementations outside of PHP.
389 if (in_array(strtolower(mcrypt_enc_get_modes_name($params['handle'])), array('cbc', 'ecb'), TRUE))
390 {
391 $block_size = mcrypt_enc_get_block_size($params['handle']);
392 $pad = $block_size - (strlen($data) % $block_size);
393 $data .= str_repeat(chr($pad), $pad);
394 }
Andrey Andreev818aedb2014-02-03 11:30:25 +0200395
Andrey Andreeve7516b02014-02-05 13:45:31 +0200396 // Work-around for yet another strange behavior in MCrypt.
397 //
398 // When encrypting in ECB mode, the IV is ignored. Yet
399 // mcrypt_enc_get_iv_size() returns a value larger than 0
400 // even if ECB is used AND mcrypt_generic_init() complains
401 // if you don't pass an IV with length equal to the said
402 // return value.
403 //
404 // This probably would've been fine (even though still wasteful),
405 // but OpenSSL isn't that dumb and we need to make the process
406 // portable, so ...
407 $data = (mcrypt_enc_get_modes_name($params['handle']) !== 'ECB')
408 ? $params['iv'].mcrypt_generic($params['handle'], $data)
409 : mcrypt_generic($params['handle'], $data);
Andrey Andreev818aedb2014-02-03 11:30:25 +0200410
411 mcrypt_generic_deinit($params['handle']);
412 if ($params['handle'] !== $this->_handle)
413 {
Andrey Andreev50ccc382014-02-04 23:30:06 +0200414 mcrypt_module_close($params['handle']);
Andrey Andreev818aedb2014-02-03 11:30:25 +0200415 }
416
417 return $data;
418 }
419
420 // --------------------------------------------------------------------
421
422 /**
423 * Encrypt via OpenSSL
424 *
425 * @param string $data Input data
426 * @param array $params Input parameters
427 * @return string
428 */
429 protected function _openssl_encrypt($data, $params)
430 {
Andrey Andreev29cade42014-02-04 14:05:58 +0200431 if (empty($params['handle']))
432 {
433 return FALSE;
434 }
Andrey Andreeve7516b02014-02-05 13:45:31 +0200435 elseif ( ! isset($params['iv']))
436 {
437 $params['iv'] = ($iv_size = openssl_cipher_iv_length($params['handle']))
Andrey Andreev8e202162014-02-05 18:59:55 +0200438 ? openssl_random_pseudo_bytes($iv_size)
Andrey Andreeve7516b02014-02-05 13:45:31 +0200439 : NULL;
440 }
Andrey Andreev29cade42014-02-04 14:05:58 +0200441
Andrey Andreev818aedb2014-02-03 11:30:25 +0200442 $data = openssl_encrypt(
443 $data,
444 $params['handle'],
445 $params['key'],
446 1, // DO NOT TOUCH!
447 $params['iv']
448 );
449
450 if ($data === FALSE)
451 {
452 return FALSE;
453 }
454
455 return $params['iv'].$data;
456 }
457
458 // --------------------------------------------------------------------
459
460 /**
461 * Decrypt
462 *
463 * @param string $data Encrypted data
464 * @param array $params Input parameters
465 * @return string
466 */
467 public function decrypt($data, array $params = NULL)
468 {
Andrey Andreev29cade42014-02-04 14:05:58 +0200469 if (($params = $this->_get_params($params)) === FALSE)
Andrey Andreev818aedb2014-02-03 11:30:25 +0200470 {
471 return FALSE;
472 }
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200473
474 if (isset($params['hmac_digest']))
475 {
Andrey Andreev29cade42014-02-04 14:05:58 +0200476 // This might look illogical, but it is done during encryption as well ...
Andrey Andreev177144f2014-02-04 18:07:34 +0200477 // The 'base64' value is effectively an inverted "raw data" parameter
Andrey Andreev29cade42014-02-04 14:05:58 +0200478 $digest_size = ($params['base64'])
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200479 ? $this->_digests[$params['hmac_digest']] * 2
480 : $this->_digests[$params['hmac_digest']];
Andrey Andreev7c554482014-02-06 02:38:27 +0200481
482 if (strlen($data) <= $digest_size)
483 {
484 return FALSE;
485 }
486
487 $hmac_input = substr($data, 0, $digest_size);
Andrey Andreev29cade42014-02-04 14:05:58 +0200488 $data = substr($data, $digest_size);
489
Andrey Andreev7c554482014-02-06 02:38:27 +0200490 isset($params['hmac_key']) OR $params['hmac_key'] = $this->hkdf($this->_key, 'sha512', NULL, NULL, 'authentication');
491 $hmac_check = hash_hmac($params['hmac_digest'], $data, $params['hmac_key'], ! $params['base64']);
492
493 // Time-attack-safe comparison
494 $diff = 0;
495 for ($i = 0; $i < $digest_size; $i++)
496 {
497 $diff |= ord($hmac_input[$i]) ^ ord($hmac_check[$i]);
498 }
499
500 if ($diff !== 0)
Andrey Andreev29cade42014-02-04 14:05:58 +0200501 {
502 return FALSE;
503 }
504 }
505
506 if ($params['base64'])
Andrey Andreev818aedb2014-02-03 11:30:25 +0200507 {
508 $data = base64_decode($data);
509 }
510
Andrey Andreeve7516b02014-02-05 13:45:31 +0200511 if (isset($params['iv']) && strncmp($params['iv'], $data, $iv_size = strlen($params['iv'])) === 0)
Andrey Andreev818aedb2014-02-03 11:30:25 +0200512 {
513 $data = substr($data, $iv_size);
514 }
515
Andrey Andreev81e10642014-02-07 01:43:36 +0200516 isset($params['key']) OR $params['key'] = $this->hkdf($this->_key, 'sha512', NULL, strlen($this->_key), 'encryption');
517
Andrey Andreev818aedb2014-02-03 11:30:25 +0200518 return $this->{'_'.$this->_driver.'_decrypt'}($data, $params);
519 }
520
521 // --------------------------------------------------------------------
522
523 /**
524 * Decrypt via MCrypt
525 *
526 * @param string $data Encrypted data
527 * @param array $params Input parameters
528 * @return string
529 */
530 protected function _mcrypt_decrypt($data, $params)
531 {
Andrey Andreev29cade42014-02-04 14:05:58 +0200532 if ( ! is_resource($params['handle']))
533 {
534 return FALSE;
535 }
Andrey Andreeve7516b02014-02-05 13:45:31 +0200536 elseif ( ! isset($params['iv']))
537 {
Andrey Andreeve8088d62014-02-06 05:01:48 +0200538 // The greater-than-1 comparison is mostly a work-around for a bug,
539 // where 1 is returned for ARCFour instead of 0.
540 if (($iv_size = mcrypt_enc_get_iv_size($params['handle'])) > 1)
Andrey Andreeve7516b02014-02-05 13:45:31 +0200541 {
542 if (mcrypt_enc_get_modes_name($params['handle']) !== 'ECB')
543 {
544 $params['iv'] = substr($data, 0, $iv_size);
545 $data = substr($data, $iv_size);
546 }
547 else
548 {
549 // MCrypt is dumb and this is ignored, only size matters
550 $params['iv'] = str_repeat("\x0", $iv_size);
551 }
552 }
553 else
554 {
555 $params['iv'] = NULL;
556 }
557 }
558
Andrey Andreeve8088d62014-02-06 05:01:48 +0200559 // CAST-128 compatibility (http://tools.ietf.org/rfc/rfc2144.txt)
560 //
561 // RFC2144 says that keys shorter than 16 bytes are to be padded with
562 // zero bytes to 16 bytes, but (surprise) MCrypt doesn't do that.
563 if ($params['cipher'] === 'cast-128' && ($kl = strlen($params['key'])) < 16)
564 {
565 $params['key'] .= str_repeat("\x0", 16 - $kl);
566 }
567
Andrey Andreeve7516b02014-02-05 13:45:31 +0200568 if (mcrypt_generic_init($params['handle'], $params['key'], $params['iv']) < 0)
Andrey Andreev818aedb2014-02-03 11:30:25 +0200569 {
570 if ($params['handle'] !== $this->_handle)
571 {
572 mcrypt_module_close($params['handle']);
573 }
574
575 return FALSE;
576 }
577
578 $data = mdecrypt_generic($params['handle'], $data);
Andrey Andreevf4017672014-02-05 18:51:15 +0200579 // Remove PKCS#7 padding, if necessary
580 if (in_array(strtolower(mcrypt_enc_get_modes_name($params['handle'])), array('cbc', 'ecb'), TRUE))
581 {
582 $data = substr($data, 0, -ord($data[strlen($data)-1]));
583 }
Andrey Andreev818aedb2014-02-03 11:30:25 +0200584
585 mcrypt_generic_deinit($params['handle']);
586 if ($params['handle'] !== $this->_handle)
587 {
Andrey Andreev50ccc382014-02-04 23:30:06 +0200588 mcrypt_module_close($params['handle']);
Andrey Andreev818aedb2014-02-03 11:30:25 +0200589 }
590
Andrey Andreevf4017672014-02-05 18:51:15 +0200591 return $data;
Andrey Andreev818aedb2014-02-03 11:30:25 +0200592 }
593
594 // --------------------------------------------------------------------
595
596 /**
597 * Decrypt via OpenSSL
598 *
599 * @param string $data Encrypted data
600 * @param array $params Input parameters
601 * @return string
602 */
603 protected function _openssl_decrypt($data, $params)
604 {
Andrey Andreeve7516b02014-02-05 13:45:31 +0200605 if ( ! isset($params['iv']))
606 {
607 if ($iv_size = openssl_cipher_iv_length($params['handle']))
608 {
609 $params['iv'] = substr($data, 0, $iv_size);
610 $data = substr($data, $iv_size);
611 }
612 else
613 {
614 $params['iv'] = NULL;
615 }
616 }
617
Andrey Andreev29cade42014-02-04 14:05:58 +0200618 return empty($params['handle'])
619 ? FALSE
620 : openssl_decrypt(
621 $data,
622 $params['handle'],
623 $params['key'],
624 1, // DO NOT TOUCH!
625 $params['iv']
626 );
Andrey Andreev818aedb2014-02-03 11:30:25 +0200627 }
628
629 // --------------------------------------------------------------------
630
631 /**
Andrey Andreev29cade42014-02-04 14:05:58 +0200632 * Get params
Andrey Andreev818aedb2014-02-03 11:30:25 +0200633 *
634 * @param array $params Input parameters
635 * @return array
636 */
Andrey Andreev29cade42014-02-04 14:05:58 +0200637 protected function _get_params($params)
Andrey Andreev818aedb2014-02-03 11:30:25 +0200638 {
639 if (empty($params))
640 {
Andrey Andreev50ccc382014-02-04 23:30:06 +0200641 return isset($this->_cipher, $this->_mode, $this->_key, $this->_handle)
Andrey Andreev29cade42014-02-04 14:05:58 +0200642 ? array(
643 'handle' => $this->_handle,
644 'cipher' => $this->_cipher,
645 'mode' => $this->_mode,
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200646 'key' => NULL,
Andrey Andreev29cade42014-02-04 14:05:58 +0200647 'base64' => TRUE,
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200648 'hmac_digest' => ($this->_mode !== 'gcm' ? 'sha512' : NULL),
649 'hmac_key' => NULL
Andrey Andreev29cade42014-02-04 14:05:58 +0200650 )
651 : FALSE;
652 }
653 elseif ( ! isset($params['cipher'], $params['mode'], $params['key']))
654 {
655 return FALSE;
656 }
657
Andrey Andreevf4017672014-02-05 18:51:15 +0200658 if (isset($params['mode']))
659 {
660 $params['mode'] = strtolower($params['mode']);
661 if ( ! isset($this->_modes[$this->_driver][$params['mode']]))
662 {
663 return FALSE;
664 }
665 else
666 {
667 $params['mode'] = $this->_modes[$this->_driver][$params['mode']];
668 }
669 }
670
Andrey Andreev81e10642014-02-07 01:43:36 +0200671 if ($params['mode'] === 'gcm' OR (isset($params['hmac']) && $params['hmac'] === FALSE))
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200672 {
673 $params['hmac_digest'] = $params['hmac_key'] = NULL;
674 }
675 else
676 {
677 if ( ! isset($params['hmac_key']))
678 {
679 return FALSE;
680 }
681 elseif (isset($params['hmac_digest']))
682 {
683 $params['hmac_digest'] = strtolower($params['hmac_digest']);
684 if ( ! isset($this->_digests[$params['hmac_digest']]))
685 {
686 return FALSE;
687 }
688 }
689 else
690 {
691 $params['hmac_digest'] = 'sha512';
692 }
693 }
694
Andrey Andreev818aedb2014-02-03 11:30:25 +0200695 $params = array(
696 'handle' => NULL,
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200697 'cipher' => $params['cipher'],
698 'mode' => $params['mode'],
699 'key' => $params['key'],
Andrey Andreev818aedb2014-02-03 11:30:25 +0200700 'iv' => isset($params['iv']) ? $params['iv'] : NULL,
Andrey Andreev4b450652014-02-10 06:59:54 +0200701 'base64' => isset($params['raw_data']) ? ! $params['raw_data'] : FALSE,
Andrey Andreev8d33a9a2014-02-05 23:11:23 +0200702 'hmac_digest' => $params['hmac_digest'],
703 'hmac_key' => $params['hmac_key']
Andrey Andreev818aedb2014-02-03 11:30:25 +0200704 );
705
Andrey Andreev818aedb2014-02-03 11:30:25 +0200706 $this->_cipher_alias($params['cipher']);
Andrey Andreev29cade42014-02-04 14:05:58 +0200707 $params['handle'] = ($params['cipher'] !== $this->_cipher OR $params['mode'] !== $this->_mode)
708 ? $this->{'_'.$this->_driver.'_get_handle'}($params['cipher'], $params['mode'])
709 : $this->_handle;
Andrey Andreev818aedb2014-02-03 11:30:25 +0200710
711 return $params;
712 }
713
714 // --------------------------------------------------------------------
715
716 /**
Andrey Andreev29cade42014-02-04 14:05:58 +0200717 * Get MCrypt handle
Andrey Andreev818aedb2014-02-03 11:30:25 +0200718 *
Andrey Andreev29cade42014-02-04 14:05:58 +0200719 * @param string $cipher Cipher name
720 * @param string $mode Encryption mode
721 * @return resource
Andrey Andreev818aedb2014-02-03 11:30:25 +0200722 */
Andrey Andreev29cade42014-02-04 14:05:58 +0200723 protected function _mcrypt_get_handle($cipher, $mode)
Andrey Andreev818aedb2014-02-03 11:30:25 +0200724 {
Andrey Andreev29cade42014-02-04 14:05:58 +0200725 return mcrypt_module_open($cipher, '', $mode, '');
726 }
Andrey Andreev818aedb2014-02-03 11:30:25 +0200727
Andrey Andreev29cade42014-02-04 14:05:58 +0200728 // --------------------------------------------------------------------
Andrey Andreev818aedb2014-02-03 11:30:25 +0200729
Andrey Andreev29cade42014-02-04 14:05:58 +0200730 /**
731 * Get OpenSSL handle
732 *
733 * @param string $cipher Cipher name
734 * @param string $mode Encryption mode
735 * @return string
736 */
737 protected function _openssl_get_handle($cipher, $mode)
738 {
739 // OpenSSL methods aren't suffixed with '-stream' for this mode
740 return ($mode === 'stream')
741 ? $cipher
742 : $cipher.'-'.$mode;
Andrey Andreev818aedb2014-02-03 11:30:25 +0200743 }
744
745 // --------------------------------------------------------------------
746
747 /**
748 * Cipher alias
749 *
750 * Tries to translate cipher names between MCrypt and OpenSSL's "dialects".
751 *
752 * @param string $cipher Cipher name
753 * @return void
754 */
755 protected function _cipher_alias(&$cipher)
756 {
757 static $dictionary;
758
759 if (empty($dictionary))
760 {
761 $dictionary = array(
762 'mcrypt' => array(
Andrey Andreev50ccc382014-02-04 23:30:06 +0200763 'aes-128' => 'rijndael-128',
764 'aes-192' => 'rijndael-128',
765 'aes-256' => 'rijndael-128',
Andrey Andreevd9a48da2014-02-05 14:10:28 +0200766 'des3-ede3' => 'tripledes',
767 'bf' => 'blowfish',
Andrey Andreeve8088d62014-02-06 05:01:48 +0200768 'cast5' => 'cast-128',
769 'rc4' => 'arcfour',
770 'rc4-40' => 'arcfour'
Andrey Andreev818aedb2014-02-03 11:30:25 +0200771 ),
772 'openssl' => array(
Andrey Andreev50ccc382014-02-04 23:30:06 +0200773 'rijndael-128' => 'aes-128',
Andrey Andreevd9a48da2014-02-05 14:10:28 +0200774 'tripledes' => 'des-ede3',
Andrey Andreeve8088d62014-02-06 05:01:48 +0200775 'blowfish' => 'bf',
776 'cast-128' => 'cast5',
777 'arcfour' => 'rc4-40',
778 'rc4' => 'rc4-40'
Andrey Andreev818aedb2014-02-03 11:30:25 +0200779 )
780 );
781
Andrey Andreevd9a48da2014-02-05 14:10:28 +0200782 // Notes:
783 //
Andrey Andreeve8088d62014-02-06 05:01:48 +0200784 // - Rijndael-128 is, at the same time all three of AES-128,
785 // AES-192 and AES-256. The only difference between them is
786 // the key size. Rijndael-192, Rijndael-256 on the other hand
787 // also have different block sizes and are NOT AES-compatible.
788 //
Andrey Andreevd9a48da2014-02-05 14:10:28 +0200789 // - Blowfish is said to be supporting key sizes between
790 // 4 and 56 bytes, but it appears that between MCrypt and
791 // OpenSSL, only those of 16 and more bytes are compatible.
Andrey Andreeve8088d62014-02-06 05:01:48 +0200792 // Also, don't know what MCrypt's 'blowfish-compat' is.
793 //
794 // - CAST-128/CAST5 produces a longer cipher when encrypted via
795 // OpenSSL, but (strangely enough) can be decrypted by either
796 // extension anyway.
797 // Also, RFC2144 says that the cipher supports key sizes
798 // between 5 and 16 bytes by the implementation actually
799 // zero-padding them to 16 bytes, but MCrypt doesn't do that.
800 //
801 // - RC4 (ARCFour) has a strange implementation under OpenSSL.
802 // Its 'rc4-40' cipher method seems to work flawlessly, yet
803 // there's another one, 'rc4' that only works with a 16-byte key.
804 //
805 // - DES is compatible, but doesn't need an alias.
Andrey Andreevd9a48da2014-02-05 14:10:28 +0200806 //
807 // Other seemingly matching ciphers between MCrypt, OpenSSL:
Andrey Andreev818aedb2014-02-03 11:30:25 +0200808 //
Andrey Andreeve8088d62014-02-06 05:01:48 +0200809 // - RC2 is NOT compatible and only an obscure forum post
810 // confirms that it is MCrypt's fault.
Andrey Andreev818aedb2014-02-03 11:30:25 +0200811 }
812
Andrey Andreev50ccc382014-02-04 23:30:06 +0200813 if (isset($dictionary[$this->_driver][$cipher]))
Andrey Andreev818aedb2014-02-03 11:30:25 +0200814 {
Andrey Andreev50ccc382014-02-04 23:30:06 +0200815 $cipher = $dictionary[$this->_driver][$cipher];
Andrey Andreev818aedb2014-02-03 11:30:25 +0200816 }
817 }
818
819 // --------------------------------------------------------------------
820
821 /**
Andrey Andreev29cade42014-02-04 14:05:58 +0200822 * HKDF
823 *
824 * @link https://tools.ietf.org/rfc/rfc5869.txt
825 * @param $key Input key
826 * @param $digest A SHA-2 hashing algorithm
827 * @param $salt Optional salt
Andrey Andreev29cade42014-02-04 14:05:58 +0200828 * @param $length Output length (defaults to the selected digest size)
Andrey Andreev4b450652014-02-10 06:59:54 +0200829 * @param $info Optional context/application-specific info
Andrey Andreev29cade42014-02-04 14:05:58 +0200830 * @return string A pseudo-random key
831 */
832 public function hkdf($key, $digest = 'sha512', $salt = NULL, $length = NULL, $info = '')
833 {
834 if ( ! isset($this->_digests[$digest]))
835 {
836 return FALSE;
837 }
838
839 if (empty($length) OR ! is_int($length))
840 {
841 $length = $this->_digests[$digest];
842 }
843 elseif ($length > (255 * $this->_digests[$digest]))
844 {
845 return FALSE;
846 }
847
848 isset($salt) OR $salt = str_repeat("\0", $this->_digests[$digest]);
849
850 $prk = hash_hmac($digest, $key, $salt, TRUE);
851 $key = '';
852 for ($key_block = '', $block_index = 1; strlen($key) < $length; $block_index++)
853 {
854 $key_block = hash_hmac($digest, $key_block.$info.chr($block_index), $prk, TRUE);
855 $key .= $key_block;
856 }
857
858 return substr($key, 0, $length);
859 }
860
861 // --------------------------------------------------------------------
862
863 /**
Andrey Andreev818aedb2014-02-03 11:30:25 +0200864 * __get() magic
865 *
866 * @param string $key Property name
867 * @return mixed
868 */
869 public function __get($key)
870 {
Andrey Andreev81e10642014-02-07 01:43:36 +0200871 // Because aliases
872 if ($key === 'mode')
873 {
874 return array_search($this->_mode, $this->_modes[$this->_driver], TRUE);
875 }
876 elseif (in_array($key, array('cipher', 'driver', 'drivers', 'digests'), TRUE))
877 {
878 return $this->{'_'.$key};
879 }
880
881 return NULL;
Andrey Andreev818aedb2014-02-03 11:30:25 +0200882 }
883
884}
885
886/* End of file Encryption.php */
887/* Location: ./system/libraries/Encryption.php */