Translated using Weblate (Slovenian)
[phpmyadmin.git] / libraries / phpseclib / Crypt / Base.php
blob83f46e3e569d497f4c2ee6f3106ba109c88e7282
1 <?php
3 /**
4 * Base Class for all Crypt_* cipher classes
6 * PHP versions 4 and 5
8 * Internally for phpseclib developers:
9 * If you plan to add a new cipher class, please note following rules:
11 * - The new Crypt_* cipher class should extend Crypt_Base
13 * - Following methods are then required to be overridden/overloaded:
15 * - _encryptBlock()
17 * - _decryptBlock()
19 * - _setupKey()
21 * - All other methods are optional to be overridden/overloaded
23 * - Look at the source code of the current ciphers how they extend Crypt_Base
24 * and take one of them as a start up for the new cipher class.
26 * - Please read all the other comments/notes/hints here also for each class var/method
28 * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
29 * of this software and associated documentation files (the "Software"), to deal
30 * in the Software without restriction, including without limitation the rights
31 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
32 * copies of the Software, and to permit persons to whom the Software is
33 * furnished to do so, subject to the following conditions:
35 * The above copyright notice and this permission notice shall be included in
36 * all copies or substantial portions of the Software.
38 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
39 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
40 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
41 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
42 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
43 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
44 * THE SOFTWARE.
46 * @category Crypt
47 * @package Crypt_Base
48 * @author Jim Wigginton <terrafrost@php.net>
49 * @author Hans-Juergen Petrich <petrich@tronic-media.com>
50 * @copyright MMVII Jim Wigginton
51 * @license http://www.opensource.org/licenses/mit-license.html MIT License
52 * @link http://phpseclib.sourceforge.net
55 /**#@+
56 * @access public
57 * @see Crypt_Base::encrypt()
58 * @see Crypt_Base::decrypt()
60 /**
61 * Encrypt / decrypt using the Counter mode.
63 * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
65 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
67 define('CRYPT_MODE_CTR', -1);
68 /**
69 * Encrypt / decrypt using the Electronic Code Book mode.
71 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
73 define('CRYPT_MODE_ECB', 1);
74 /**
75 * Encrypt / decrypt using the Code Book Chaining mode.
77 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
79 define('CRYPT_MODE_CBC', 2);
80 /**
81 * Encrypt / decrypt using the Cipher Feedback mode.
83 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
85 define('CRYPT_MODE_CFB', 3);
86 /**
87 * Encrypt / decrypt using the Output Feedback mode.
89 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
91 define('CRYPT_MODE_OFB', 4);
92 /**
93 * Encrypt / decrypt using streaming mode.
96 define('CRYPT_MODE_STREAM', 5);
97 /**#@-*/
99 /**#@+
100 * @access private
101 * @see Crypt_Base::Crypt_Base()
104 * Base value for the internal implementation $engine switch
106 define('CRYPT_MODE_INTERNAL', 1);
108 * Base value for the mcrypt implementation $engine switch
110 define('CRYPT_MODE_MCRYPT', 2);
111 /**#@-*/
114 * Base Class for all Crypt_* cipher classes
116 * @package Crypt_Base
117 * @author Jim Wigginton <terrafrost@php.net>
118 * @author Hans-Juergen Petrich <petrich@tronic-media.com>
119 * @access public
121 class Crypt_Base
124 * The Encryption Mode
126 * @see Crypt_Base::Crypt_Base()
127 * @var Integer
128 * @access private
130 var $mode;
133 * The Block Length of the block cipher
135 * @var Integer
136 * @access private
138 var $block_size = 16;
141 * The Key
143 * @see Crypt_Base::setKey()
144 * @var String
145 * @access private
147 var $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
150 * The Initialization Vector
152 * @see Crypt_Base::setIV()
153 * @var String
154 * @access private
156 var $iv;
159 * A "sliding" Initialization Vector
161 * @see Crypt_Base::enableContinuousBuffer()
162 * @see Crypt_Base::_clearBuffers()
163 * @var String
164 * @access private
166 var $encryptIV;
169 * A "sliding" Initialization Vector
171 * @see Crypt_Base::enableContinuousBuffer()
172 * @see Crypt_Base::_clearBuffers()
173 * @var String
174 * @access private
176 var $decryptIV;
179 * Continuous Buffer status
181 * @see Crypt_Base::enableContinuousBuffer()
182 * @var Boolean
183 * @access private
185 var $continuousBuffer = false;
188 * Encryption buffer for CTR, OFB and CFB modes
190 * @see Crypt_Base::encrypt()
191 * @see Crypt_Base::_clearBuffers()
192 * @var Array
193 * @access private
195 var $enbuffer;
198 * Decryption buffer for CTR, OFB and CFB modes
200 * @see Crypt_Base::decrypt()
201 * @see Crypt_Base::_clearBuffers()
202 * @var Array
203 * @access private
205 var $debuffer;
208 * mcrypt resource for encryption
210 * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
211 * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
213 * @see Crypt_Base::encrypt()
214 * @var Resource
215 * @access private
217 var $enmcrypt;
220 * mcrypt resource for decryption
222 * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
223 * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
225 * @see Crypt_Base::decrypt()
226 * @var Resource
227 * @access private
229 var $demcrypt;
232 * Does the enmcrypt resource need to be (re)initialized?
234 * @see Crypt_Twofish::setKey()
235 * @see Crypt_Twofish::setIV()
236 * @var Boolean
237 * @access private
239 var $enchanged = true;
242 * Does the demcrypt resource need to be (re)initialized?
244 * @see Crypt_Twofish::setKey()
245 * @see Crypt_Twofish::setIV()
246 * @var Boolean
247 * @access private
249 var $dechanged = true;
252 * mcrypt resource for CFB mode
254 * mcrypt's CFB mode, in (and only in) buffered context,
255 * is broken, so phpseclib implements the CFB mode by it self,
256 * even when the mcrypt php extension is available.
258 * In order to do the CFB-mode work (fast) phpseclib
259 * use a separate ECB-mode mcrypt resource.
261 * @link http://phpseclib.sourceforge.net/cfb-demo.phps
262 * @see Crypt_Base::encrypt()
263 * @see Crypt_Base::decrypt()
264 * @see Crypt_Base::_setupMcrypt()
265 * @var Resource
266 * @access private
268 var $ecb;
271 * Optimizing value while CFB-encrypting
273 * Only relevant if $continuousBuffer enabled
274 * and $engine == CRYPT_MODE_MCRYPT
276 * It's faster to re-init $enmcrypt if
277 * $buffer bytes > $cfb_init_len than
278 * using the $ecb resource furthermore.
280 * This value depends of the chosen cipher
281 * and the time it would be needed for it's
282 * initialization [by mcrypt_generic_init()]
283 * which, typically, depends on the complexity
284 * on its internaly Key-expanding algorithm.
286 * @see Crypt_Base::encrypt()
287 * @var Integer
288 * @access private
290 var $cfb_init_len = 600;
293 * Does internal cipher state need to be (re)initialized?
295 * @see setKey()
296 * @see setIV()
297 * @see disableContinuousBuffer()
298 * @var Boolean
299 * @access private
301 var $changed = true;
304 * Padding status
306 * @see Crypt_Base::enablePadding()
307 * @var Boolean
308 * @access private
310 var $padding = true;
313 * Is the mode one that is paddable?
315 * @see Crypt_Base::Crypt_Base()
316 * @var Boolean
317 * @access private
319 var $paddable = false;
322 * Holds which crypt engine internaly should be use,
323 * which will be determined automatically on __construct()
325 * Currently available $engines are:
326 * - CRYPT_MODE_MCRYPT (fast, php-extension: mcrypt, extension_loaded('mcrypt') required)
327 * - CRYPT_MODE_INTERNAL (slower, pure php-engine, no php-extension required)
329 * In the pipeline... maybe. But currently not available:
330 * - CRYPT_MODE_OPENSSL (very fast, php-extension: openssl, extension_loaded('openssl') required)
332 * If possible, CRYPT_MODE_MCRYPT will be used for each cipher.
333 * Otherwise CRYPT_MODE_INTERNAL
335 * @see Crypt_Base::encrypt()
336 * @see Crypt_Base::decrypt()
337 * @var Integer
338 * @access private
340 var $engine;
343 * The mcrypt specific name of the cipher
345 * Only used if $engine == CRYPT_MODE_MCRYPT
347 * @link http://www.php.net/mcrypt_module_open
348 * @link http://www.php.net/mcrypt_list_algorithms
349 * @see Crypt_Base::_setupMcrypt()
350 * @var String
351 * @access private
353 var $cipher_name_mcrypt;
356 * The default password key_size used by setPassword()
358 * @see Crypt_Base::setPassword()
359 * @var Integer
360 * @access private
362 var $password_key_size = 32;
365 * The default salt used by setPassword()
367 * @see Crypt_Base::setPassword()
368 * @var String
369 * @access private
371 var $password_default_salt = 'phpseclib/salt';
374 * The namespace used by the cipher for its constants.
376 * ie: AES.php is using CRYPT_AES_MODE_* for its constants
377 * so $const_namespace is AES
379 * DES.php is using CRYPT_DES_MODE_* for its constants
380 * so $const_namespace is DES... and so on
382 * All CRYPT_<$const_namespace>_MODE_* are aliases of
383 * the generic CRYPT_MODE_* constants, so both could be used
384 * for each cipher.
386 * Example:
387 * $aes = new Crypt_AES(CRYPT_AES_MODE_CFB); // $aes will operate in cfb mode
388 * $aes = new Crypt_AES(CRYPT_MODE_CFB); // identical
390 * @see Crypt_Base::Crypt_Base()
391 * @var String
392 * @access private
394 var $const_namespace;
397 * The name of the performance-optimized callback function
399 * Used by encrypt() / decrypt()
400 * only if $engine == CRYPT_MODE_INTERNAL
402 * @see Crypt_Base::encrypt()
403 * @see Crypt_Base::decrypt()
404 * @see Crypt_Base::_setupInlineCrypt()
405 * @see Crypt_Base::$use_inline_crypt
406 * @var Callback
407 * @access private
409 var $inline_crypt;
412 * Holds whether performance-optimized $inline_crypt() can/should be used.
414 * @see Crypt_Base::encrypt()
415 * @see Crypt_Base::decrypt()
416 * @see Crypt_Base::inline_crypt
417 * @var mixed
418 * @access private
420 var $use_inline_crypt;
423 * Default Constructor.
425 * Determines whether or not the mcrypt extension should be used.
427 * $mode could be:
429 * - CRYPT_MODE_ECB
431 * - CRYPT_MODE_CBC
433 * - CRYPT_MODE_CTR
435 * - CRYPT_MODE_CFB
437 * - CRYPT_MODE_OFB
439 * (or the alias constants of the chosen cipher, for example for AES: CRYPT_AES_MODE_ECB or CRYPT_AES_MODE_CBC ...)
441 * If not explicitly set, CRYPT_MODE_CBC will be used.
443 * @param optional Integer $mode
444 * @access public
446 function Crypt_Base($mode = CRYPT_MODE_CBC)
448 $const_crypt_mode = 'CRYPT_' . $this->const_namespace . '_MODE';
450 // Determining the availibility of mcrypt support for the cipher
451 if (!defined($const_crypt_mode)) {
452 switch (true) {
453 case extension_loaded('mcrypt') && in_array($this->cipher_name_mcrypt, mcrypt_list_algorithms()):
454 define($const_crypt_mode, CRYPT_MODE_MCRYPT);
455 break;
456 default:
457 define($const_crypt_mode, CRYPT_MODE_INTERNAL);
461 // Determining which internal $engine should be used.
462 // The fastes possible first.
463 switch (true) {
464 case empty($this->cipher_name_mcrypt): // The cipher module has no mcrypt-engine support at all so we force CRYPT_MODE_INTERNAL
465 $this->engine = CRYPT_MODE_INTERNAL;
466 break;
467 case constant($const_crypt_mode) == CRYPT_MODE_MCRYPT:
468 $this->engine = CRYPT_MODE_MCRYPT;
469 break;
470 default:
471 $this->engine = CRYPT_MODE_INTERNAL;
474 // $mode dependent settings
475 switch ($mode) {
476 case CRYPT_MODE_ECB:
477 $this->paddable = true;
478 $this->mode = $mode;
479 break;
480 case CRYPT_MODE_CTR:
481 case CRYPT_MODE_CFB:
482 case CRYPT_MODE_OFB:
483 case CRYPT_MODE_STREAM:
484 $this->mode = $mode;
485 break;
486 case CRYPT_MODE_CBC:
487 default:
488 $this->paddable = true;
489 $this->mode = CRYPT_MODE_CBC;
492 // Determining whether inline crypting can be used by the cipher
493 if ($this->use_inline_crypt !== false && function_exists('create_function')) {
494 $this->use_inline_crypt = true;
499 * Sets the initialization vector. (optional)
501 * SetIV is not required when CRYPT_MODE_ECB (or ie for AES: CRYPT_AES_MODE_ECB) is being used. If not explicitly set, it'll be assumed
502 * to be all zero's.
504 * Note: Could, but not must, extend by the child Crypt_* class
506 * @access public
507 * @param String $iv
509 function setIV($iv)
511 if ($this->mode == CRYPT_MODE_ECB) {
512 return;
515 $this->iv = $iv;
516 $this->changed = true;
520 * Sets the key.
522 * The min/max length(s) of the key depends on the cipher which is used.
523 * If the key not fits the length(s) of the cipher it will paded with null bytes
524 * up to the closest valid key length. If the key is more than max length,
525 * we trim the excess bits.
527 * If the key is not explicitly set, it'll be assumed to be all null bytes.
529 * Note: Could, but not must, extend by the child Crypt_* class
531 * @access public
532 * @param String $key
534 function setKey($key)
536 $this->key = $key;
537 $this->changed = true;
541 * Sets the password.
543 * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows:
544 * {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2}:
545 * $hash, $salt, $count, $dkLen
547 * Where $hash (default = sha1) currently supports the following hashes: see: Crypt/Hash.php
549 * Note: Could, but not must, extend by the child Crypt_* class
551 * @see Crypt/Hash.php
552 * @param String $password
553 * @param optional String $method
554 * @access public
556 function setPassword($password, $method = 'pbkdf2')
558 $key = '';
560 switch ($method) {
561 default: // 'pbkdf2'
562 $func_args = func_get_args();
564 // Hash function
565 $hash = isset($func_args[2]) ? $func_args[2] : 'sha1';
567 // WPA and WPA2 use the SSID as the salt
568 $salt = isset($func_args[3]) ? $func_args[3] : $this->password_default_salt;
570 // RFC2898#section-4.2 uses 1,000 iterations by default
571 // WPA and WPA2 use 4,096.
572 $count = isset($func_args[4]) ? $func_args[4] : 1000;
574 // Keylength
575 $dkLen = isset($func_args[5]) ? $func_args[5] : $this->password_key_size;
577 // Determining if php[>=5.5.0]'s hash_pbkdf2() function avail- and useable
578 switch (true) {
579 case !function_exists('hash_pbkdf2'):
580 case !function_exists('hash_algos'):
581 case !in_array($hash, hash_algos()):
582 if (!class_exists('Crypt_Hash')) {
583 include_once 'Crypt/Hash.php';
585 $i = 1;
586 while (strlen($key) < $dkLen) {
587 $hmac = new Crypt_Hash();
588 $hmac->setHash($hash);
589 $hmac->setKey($password);
590 $f = $u = $hmac->hash($salt . pack('N', $i++));
591 for ($j = 2; $j <= $count; ++$j) {
592 $u = $hmac->hash($u);
593 $f^= $u;
595 $key.= $f;
597 $key = substr($key, 0, $dkLen);
598 break;
599 default:
600 $key = hash_pbkdf2($hash, $password, $salt, $count, $dkLen, true);
604 $this->setKey($key);
608 * Encrypts a message.
610 * $plaintext will be padded with additional bytes such that it's length is a multiple of the block size. Other cipher
611 * implementations may or may not pad in the same manner. Other common approaches to padding and the reasons why it's
612 * necessary are discussed in the following
613 * URL:
615 * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
617 * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does.
618 * strlen($plaintext) will still need to be a multiple of the block size, however, arbitrary values can be added to make it that
619 * length.
621 * Note: Could, but not must, extend by the child Crypt_* class
623 * @see Crypt_Base::decrypt()
624 * @access public
625 * @param String $plaintext
626 * @return String $cipertext
628 function encrypt($plaintext)
630 if ($this->engine == CRYPT_MODE_MCRYPT) {
631 if ($this->changed) {
632 $this->_setupMcrypt();
633 $this->changed = false;
635 if ($this->enchanged) {
636 mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
637 $this->enchanged = false;
640 // re: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
641 // using mcrypt's default handing of CFB the above would output two different things. using phpseclib's
642 // rewritten CFB implementation the above outputs the same thing twice.
643 if ($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer) {
644 $block_size = $this->block_size;
645 $iv = &$this->encryptIV;
646 $pos = &$this->enbuffer['pos'];
647 $len = strlen($plaintext);
648 $ciphertext = '';
649 $i = 0;
650 if ($pos) {
651 $orig_pos = $pos;
652 $max = $block_size - $pos;
653 if ($len >= $max) {
654 $i = $max;
655 $len-= $max;
656 $pos = 0;
657 } else {
658 $i = $len;
659 $pos+= $len;
660 $len = 0;
662 $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
663 $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
664 $this->enbuffer['enmcrypt_init'] = true;
666 if ($len >= $block_size) {
667 if ($this->enbuffer['enmcrypt_init'] === false || $len > $this->cfb_init_len) {
668 if ($this->enbuffer['enmcrypt_init'] === true) {
669 mcrypt_generic_init($this->enmcrypt, $this->key, $iv);
670 $this->enbuffer['enmcrypt_init'] = false;
672 $ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % $block_size));
673 $iv = substr($ciphertext, -$block_size);
674 $len%= $block_size;
675 } else {
676 while ($len >= $block_size) {
677 $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, $block_size);
678 $ciphertext.= $iv;
679 $len-= $block_size;
680 $i+= $block_size;
685 if ($len) {
686 $iv = mcrypt_generic($this->ecb, $iv);
687 $block = $iv ^ substr($plaintext, -$len);
688 $iv = substr_replace($iv, $block, 0, $len);
689 $ciphertext.= $block;
690 $pos = $len;
693 return $ciphertext;
696 if ($this->paddable) {
697 $plaintext = $this->_pad($plaintext);
700 $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
702 if (!$this->continuousBuffer) {
703 mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
706 return $ciphertext;
709 if ($this->changed) {
710 $this->_setup();
711 $this->changed = false;
713 if ($this->use_inline_crypt) {
714 $inline = $this->inline_crypt;
715 return $inline('encrypt', $this, $plaintext);
717 if ($this->paddable) {
718 $plaintext = $this->_pad($plaintext);
721 $buffer = &$this->enbuffer;
722 $block_size = $this->block_size;
723 $ciphertext = '';
724 switch ($this->mode) {
725 case CRYPT_MODE_ECB:
726 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
727 $ciphertext.= $this->_encryptBlock(substr($plaintext, $i, $block_size));
729 break;
730 case CRYPT_MODE_CBC:
731 $xor = $this->encryptIV;
732 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
733 $block = substr($plaintext, $i, $block_size);
734 $block = $this->_encryptBlock($block ^ $xor);
735 $xor = $block;
736 $ciphertext.= $block;
738 if ($this->continuousBuffer) {
739 $this->encryptIV = $xor;
741 break;
742 case CRYPT_MODE_CTR:
743 $xor = $this->encryptIV;
744 if (strlen($buffer['encrypted'])) {
745 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
746 $block = substr($plaintext, $i, $block_size);
747 if (strlen($block) > strlen($buffer['encrypted'])) {
748 $buffer['encrypted'].= $this->_encryptBlock($this->_generateXor($xor, $block_size));
750 $key = $this->_stringShift($buffer['encrypted'], $block_size);
751 $ciphertext.= $block ^ $key;
753 } else {
754 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
755 $block = substr($plaintext, $i, $block_size);
756 $key = $this->_encryptBlock($this->_generateXor($xor, $block_size));
757 $ciphertext.= $block ^ $key;
760 if ($this->continuousBuffer) {
761 $this->encryptIV = $xor;
762 if ($start = strlen($plaintext) % $block_size) {
763 $buffer['encrypted'] = substr($key, $start) . $buffer['encrypted'];
766 break;
767 case CRYPT_MODE_CFB:
768 // cfb loosely routines inspired by openssl's:
769 // {@link http://cvs.openssl.org/fileview?f=openssl/crypto/modes/cfb128.c&v=1.3.2.2.2.1}
770 if ($this->continuousBuffer) {
771 $iv = &$this->encryptIV;
772 $pos = &$buffer['pos'];
773 } else {
774 $iv = $this->encryptIV;
775 $pos = 0;
777 $len = strlen($plaintext);
778 $i = 0;
779 if ($pos) {
780 $orig_pos = $pos;
781 $max = $block_size - $pos;
782 if ($len >= $max) {
783 $i = $max;
784 $len-= $max;
785 $pos = 0;
786 } else {
787 $i = $len;
788 $pos+= $len;
789 $len = 0;
791 // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
792 $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
793 $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
795 while ($len >= $block_size) {
796 $iv = $this->_encryptBlock($iv) ^ substr($plaintext, $i, $block_size);
797 $ciphertext.= $iv;
798 $len-= $block_size;
799 $i+= $block_size;
801 if ($len) {
802 $iv = $this->_encryptBlock($iv);
803 $block = $iv ^ substr($plaintext, $i);
804 $iv = substr_replace($iv, $block, 0, $len);
805 $ciphertext.= $block;
806 $pos = $len;
808 break;
809 case CRYPT_MODE_OFB:
810 $xor = $this->encryptIV;
811 if (strlen($buffer['xor'])) {
812 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
813 $block = substr($plaintext, $i, $block_size);
814 if (strlen($block) > strlen($buffer['xor'])) {
815 $xor = $this->_encryptBlock($xor);
816 $buffer['xor'].= $xor;
818 $key = $this->_stringShift($buffer['xor'], $block_size);
819 $ciphertext.= $block ^ $key;
821 } else {
822 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
823 $xor = $this->_encryptBlock($xor);
824 $ciphertext.= substr($plaintext, $i, $block_size) ^ $xor;
826 $key = $xor;
828 if ($this->continuousBuffer) {
829 $this->encryptIV = $xor;
830 if ($start = strlen($plaintext) % $block_size) {
831 $buffer['xor'] = substr($key, $start) . $buffer['xor'];
834 break;
835 case CRYPT_MODE_STREAM:
836 $ciphertext = $this->_encryptBlock($plaintext);
837 break;
840 return $ciphertext;
844 * Decrypts a message.
846 * If strlen($ciphertext) is not a multiple of the block size, null bytes will be added to the end of the string until
847 * it is.
849 * Note: Could, but not must, extend by the child Crypt_* class
851 * @see Crypt_Base::encrypt()
852 * @access public
853 * @param String $ciphertext
854 * @return String $plaintext
856 function decrypt($ciphertext)
858 if ($this->engine == CRYPT_MODE_MCRYPT) {
859 $block_size = $this->block_size;
860 if ($this->changed) {
861 $this->_setupMcrypt();
862 $this->changed = false;
864 if ($this->dechanged) {
865 mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
866 $this->dechanged = false;
869 if ($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer) {
870 $iv = &$this->decryptIV;
871 $pos = &$this->debuffer['pos'];
872 $len = strlen($ciphertext);
873 $plaintext = '';
874 $i = 0;
875 if ($pos) {
876 $orig_pos = $pos;
877 $max = $block_size - $pos;
878 if ($len >= $max) {
879 $i = $max;
880 $len-= $max;
881 $pos = 0;
882 } else {
883 $i = $len;
884 $pos+= $len;
885 $len = 0;
887 // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
888 $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
889 $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
891 if ($len >= $block_size) {
892 $cb = substr($ciphertext, $i, $len - $len % $block_size);
893 $plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
894 $iv = substr($cb, -$block_size);
895 $len%= $block_size;
897 if ($len) {
898 $iv = mcrypt_generic($this->ecb, $iv);
899 $plaintext.= $iv ^ substr($ciphertext, -$len);
900 $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len);
901 $pos = $len;
904 return $plaintext;
907 if ($this->paddable) {
908 // we pad with chr(0) since that's what mcrypt_generic does. to quote from {@link http://www.php.net/function.mcrypt-generic}:
909 // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
910 $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($block_size - strlen($ciphertext) % $block_size) % $block_size, chr(0));
913 $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
915 if (!$this->continuousBuffer) {
916 mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
919 return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
922 if ($this->changed) {
923 $this->_setup();
924 $this->changed = false;
926 if ($this->use_inline_crypt) {
927 $inline = $this->inline_crypt;
928 return $inline('decrypt', $this, $ciphertext);
931 $block_size = $this->block_size;
932 if ($this->paddable) {
933 // we pad with chr(0) since that's what mcrypt_generic does [...]
934 $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($block_size - strlen($ciphertext) % $block_size) % $block_size, chr(0));
937 $buffer = &$this->debuffer;
938 $plaintext = '';
939 switch ($this->mode) {
940 case CRYPT_MODE_ECB:
941 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
942 $plaintext.= $this->_decryptBlock(substr($ciphertext, $i, $block_size));
944 break;
945 case CRYPT_MODE_CBC:
946 $xor = $this->decryptIV;
947 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
948 $block = substr($ciphertext, $i, $block_size);
949 $plaintext.= $this->_decryptBlock($block) ^ $xor;
950 $xor = $block;
952 if ($this->continuousBuffer) {
953 $this->decryptIV = $xor;
955 break;
956 case CRYPT_MODE_CTR:
957 $xor = $this->decryptIV;
958 if (strlen($buffer['ciphertext'])) {
959 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
960 $block = substr($ciphertext, $i, $block_size);
961 if (strlen($block) > strlen($buffer['ciphertext'])) {
962 $buffer['ciphertext'].= $this->_encryptBlock($this->_generateXor($xor, $block_size));
964 $key = $this->_stringShift($buffer['ciphertext'], $block_size);
965 $plaintext.= $block ^ $key;
967 } else {
968 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
969 $block = substr($ciphertext, $i, $block_size);
970 $key = $this->_encryptBlock($this->_generateXor($xor, $block_size));
971 $plaintext.= $block ^ $key;
974 if ($this->continuousBuffer) {
975 $this->decryptIV = $xor;
976 if ($start = strlen($ciphertext) % $block_size) {
977 $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext'];
980 break;
981 case CRYPT_MODE_CFB:
982 if ($this->continuousBuffer) {
983 $iv = &$this->decryptIV;
984 $pos = &$buffer['pos'];
985 } else {
986 $iv = $this->decryptIV;
987 $pos = 0;
989 $len = strlen($ciphertext);
990 $i = 0;
991 if ($pos) {
992 $orig_pos = $pos;
993 $max = $block_size - $pos;
994 if ($len >= $max) {
995 $i = $max;
996 $len-= $max;
997 $pos = 0;
998 } else {
999 $i = $len;
1000 $pos+= $len;
1001 $len = 0;
1003 // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
1004 $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
1005 $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
1007 while ($len >= $block_size) {
1008 $iv = $this->_encryptBlock($iv);
1009 $cb = substr($ciphertext, $i, $block_size);
1010 $plaintext.= $iv ^ $cb;
1011 $iv = $cb;
1012 $len-= $block_size;
1013 $i+= $block_size;
1015 if ($len) {
1016 $iv = $this->_encryptBlock($iv);
1017 $plaintext.= $iv ^ substr($ciphertext, $i);
1018 $iv = substr_replace($iv, substr($ciphertext, $i), 0, $len);
1019 $pos = $len;
1021 break;
1022 case CRYPT_MODE_OFB:
1023 $xor = $this->decryptIV;
1024 if (strlen($buffer['xor'])) {
1025 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
1026 $block = substr($ciphertext, $i, $block_size);
1027 if (strlen($block) > strlen($buffer['xor'])) {
1028 $xor = $this->_encryptBlock($xor);
1029 $buffer['xor'].= $xor;
1031 $key = $this->_stringShift($buffer['xor'], $block_size);
1032 $plaintext.= $block ^ $key;
1034 } else {
1035 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
1036 $xor = $this->_encryptBlock($xor);
1037 $plaintext.= substr($ciphertext, $i, $block_size) ^ $xor;
1039 $key = $xor;
1041 if ($this->continuousBuffer) {
1042 $this->decryptIV = $xor;
1043 if ($start = strlen($ciphertext) % $block_size) {
1044 $buffer['xor'] = substr($key, $start) . $buffer['xor'];
1047 break;
1048 case CRYPT_MODE_STREAM:
1049 $plaintext = $this->_decryptBlock($ciphertext);
1050 break;
1052 return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
1056 * Pad "packets".
1058 * Block ciphers working by encrypting between their specified [$this->]block_size at a time
1059 * If you ever need to encrypt or decrypt something that isn't of the proper length, it becomes necessary to
1060 * pad the input so that it is of the proper length.
1062 * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH,
1063 * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping
1064 * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is
1065 * transmitted separately)
1067 * @see Crypt_Base::disablePadding()
1068 * @access public
1070 function enablePadding()
1072 $this->padding = true;
1076 * Do not pad packets.
1078 * @see Crypt_Base::enablePadding()
1079 * @access public
1081 function disablePadding()
1083 $this->padding = false;
1087 * Treat consecutive "packets" as if they are a continuous buffer.
1089 * Say you have a 32-byte plaintext $plaintext. Using the default behavior, the two following code snippets
1090 * will yield different outputs:
1092 * <code>
1093 * echo $rijndael->encrypt(substr($plaintext, 0, 16));
1094 * echo $rijndael->encrypt(substr($plaintext, 16, 16));
1095 * </code>
1096 * <code>
1097 * echo $rijndael->encrypt($plaintext);
1098 * </code>
1100 * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
1101 * another, as demonstrated with the following:
1103 * <code>
1104 * $rijndael->encrypt(substr($plaintext, 0, 16));
1105 * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
1106 * </code>
1107 * <code>
1108 * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
1109 * </code>
1111 * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
1112 * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
1113 * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
1115 * Put another way, when the continuous buffer is enabled, the state of the Crypt_*() object changes after each
1116 * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
1117 * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
1118 * however, they are also less intuitive and more likely to cause you problems.
1120 * Note: Could, but not must, extend by the child Crypt_* class
1122 * @see Crypt_Base::disableContinuousBuffer()
1123 * @access public
1125 function enableContinuousBuffer()
1127 if ($this->mode == CRYPT_MODE_ECB) {
1128 return;
1131 $this->continuousBuffer = true;
1135 * Treat consecutive packets as if they are a discontinuous buffer.
1137 * The default behavior.
1139 * Note: Could, but not must, extend by the child Crypt_* class
1141 * @see Crypt_Base::enableContinuousBuffer()
1142 * @access public
1144 function disableContinuousBuffer()
1146 if ($this->mode == CRYPT_MODE_ECB) {
1147 return;
1149 if (!$this->continuousBuffer) {
1150 return;
1153 $this->continuousBuffer = false;
1154 $this->changed = true;
1158 * Encrypts a block
1160 * Note: Must extend by the child Crypt_* class
1162 * @access private
1163 * @param String $in
1164 * @return String
1166 function _encryptBlock($in)
1168 user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
1172 * Decrypts a block
1174 * Note: Must extend by the child Crypt_* class
1176 * @access private
1177 * @param String $in
1178 * @return String
1180 function _decryptBlock($in)
1182 user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
1186 * Setup the key (expansion)
1188 * Only used if $engine == CRYPT_MODE_INTERNAL
1190 * Note: Must extend by the child Crypt_* class
1192 * @see Crypt_Base::_setup()
1193 * @access private
1195 function _setupKey()
1197 user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
1201 * Setup the CRYPT_MODE_INTERNAL $engine
1203 * (re)init, if necessary, the internal cipher $engine and flush all $buffers
1204 * Used (only) if $engine == CRYPT_MODE_INTERNAL
1206 * _setup() will be called each time if $changed === true
1207 * typically this happens when using one or more of following public methods:
1209 * - setKey()
1211 * - setIV()
1213 * - disableContinuousBuffer()
1215 * - First run of encrypt() / decrypt() with no init-settings
1217 * Internally: _setup() is called always before(!) en/decryption.
1219 * Note: Could, but not must, extend by the child Crypt_* class
1221 * @see setKey()
1222 * @see setIV()
1223 * @see disableContinuousBuffer()
1224 * @access private
1226 function _setup()
1228 $this->_clearBuffers();
1229 $this->_setupKey();
1231 if ($this->use_inline_crypt) {
1232 $this->_setupInlineCrypt();
1237 * Setup the CRYPT_MODE_MCRYPT $engine
1239 * (re)init, if necessary, the (ext)mcrypt resources and flush all $buffers
1240 * Used (only) if $engine = CRYPT_MODE_MCRYPT
1242 * _setupMcrypt() will be called each time if $changed === true
1243 * typically this happens when using one or more of following public methods:
1245 * - setKey()
1247 * - setIV()
1249 * - disableContinuousBuffer()
1251 * - First run of encrypt() / decrypt()
1254 * Note: Could, but not must, extend by the child Crypt_* class
1256 * @see setKey()
1257 * @see setIV()
1258 * @see disableContinuousBuffer()
1259 * @access private
1261 function _setupMcrypt()
1263 $this->_clearBuffers();
1264 $this->enchanged = $this->dechanged = true;
1266 if (!isset($this->enmcrypt)) {
1267 static $mcrypt_modes = array(
1268 CRYPT_MODE_CTR => 'ctr',
1269 CRYPT_MODE_ECB => MCRYPT_MODE_ECB,
1270 CRYPT_MODE_CBC => MCRYPT_MODE_CBC,
1271 CRYPT_MODE_CFB => 'ncfb',
1272 CRYPT_MODE_OFB => MCRYPT_MODE_NOFB,
1273 CRYPT_MODE_STREAM => MCRYPT_MODE_STREAM,
1276 $this->demcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
1277 $this->enmcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
1279 // we need the $ecb mcrypt resource (only) in MODE_CFB with enableContinuousBuffer()
1280 // to workaround mcrypt's broken ncfb implementation in buffered mode
1281 // see: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
1282 if ($this->mode == CRYPT_MODE_CFB) {
1283 $this->ecb = mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, '');
1286 } // else should mcrypt_generic_deinit be called?
1288 if ($this->mode == CRYPT_MODE_CFB) {
1289 mcrypt_generic_init($this->ecb, $this->key, str_repeat("\0", $this->block_size));
1294 * Pads a string
1296 * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize.
1297 * $this->block_size - (strlen($text) % $this->block_size) bytes are added, each of which is equal to
1298 * chr($this->block_size - (strlen($text) % $this->block_size)
1300 * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless
1301 * and padding will, hence forth, be enabled.
1303 * @see Crypt_Base::_unpad()
1304 * @param String $text
1305 * @access private
1306 * @return String
1308 function _pad($text)
1310 $length = strlen($text);
1312 if (!$this->padding) {
1313 if ($length % $this->block_size == 0) {
1314 return $text;
1315 } else {
1316 user_error("The plaintext's length ($length) is not a multiple of the block size ({$this->block_size})");
1317 $this->padding = true;
1321 $pad = $this->block_size - ($length % $this->block_size);
1323 return str_pad($text, $length + $pad, chr($pad));
1327 * Unpads a string.
1329 * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong
1330 * and false will be returned.
1332 * @see Crypt_Base::_pad()
1333 * @param String $text
1334 * @access private
1335 * @return String
1337 function _unpad($text)
1339 if (!$this->padding) {
1340 return $text;
1343 $length = ord($text[strlen($text) - 1]);
1345 if (!$length || $length > $this->block_size) {
1346 return false;
1349 return substr($text, 0, -$length);
1353 * Clears internal buffers
1355 * Clearing/resetting the internal buffers is done everytime
1356 * after disableContinuousBuffer() or on cipher $engine (re)init
1357 * ie after setKey() or setIV()
1359 * Note: Could, but not must, extend by the child Crypt_* class
1361 * @access public
1363 function _clearBuffers()
1365 $this->enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
1366 $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true);
1368 // mcrypt's handling of invalid's $iv:
1369 // $this->encryptIV = $this->decryptIV = strlen($this->iv) == $this->block_size ? $this->iv : str_repeat("\0", $this->block_size);
1370 $this->encryptIV = $this->decryptIV = str_pad(substr($this->iv, 0, $this->block_size), $this->block_size, "\0");
1374 * String Shift
1376 * Inspired by array_shift
1378 * @param String $string
1379 * @param optional Integer $index
1380 * @access private
1381 * @return String
1383 function _stringShift(&$string, $index = 1)
1385 $substr = substr($string, 0, $index);
1386 $string = substr($string, $index);
1387 return $substr;
1391 * Generate CTR XOR encryption key
1393 * Encrypt the output of this and XOR it against the ciphertext / plaintext to get the
1394 * plaintext / ciphertext in CTR mode.
1396 * @see Crypt_Base::decrypt()
1397 * @see Crypt_Base::encrypt()
1398 * @param String $iv
1399 * @param Integer $length
1400 * @access private
1401 * @return String $xor
1403 function _generateXor(&$iv, $length)
1405 $xor = '';
1406 $block_size = $this->block_size;
1407 $num_blocks = floor(($length + ($block_size - 1)) / $block_size);
1408 for ($i = 0; $i < $num_blocks; $i++) {
1409 $xor.= $iv;
1410 for ($j = 4; $j <= $block_size; $j+= 4) {
1411 $temp = substr($iv, -$j, 4);
1412 switch ($temp) {
1413 case "\xFF\xFF\xFF\xFF":
1414 $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4);
1415 break;
1416 case "\x7F\xFF\xFF\xFF":
1417 $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4);
1418 break 2;
1419 default:
1420 extract(unpack('Ncount', $temp));
1421 $iv = substr_replace($iv, pack('N', $count + 1), -$j, 4);
1422 break 2;
1427 return $xor;
1431 * Setup the performance-optimized function for de/encrypt()
1433 * Stores the created (or existing) callback function-name
1434 * in $this->inline_crypt
1436 * Internally for phpseclib developers:
1438 * _setupInlineCrypt() would be called only if:
1440 * - $engine == CRYPT_MODE_INTERNAL and
1442 * - $use_inline_crypt === true
1444 * - each time on _setup(), after(!) _setupKey()
1447 * This ensures that _setupInlineCrypt() has always a
1448 * full ready2go initializated internal cipher $engine state
1449 * where, for example, the keys allready expanded,
1450 * keys/block_size calculated and such.
1452 * It is, each time if called, the responsibility of _setupInlineCrypt():
1454 * - to set $this->inline_crypt to a valid and fully working callback function
1455 * as a (faster) replacement for encrypt() / decrypt()
1457 * - NOT to create unlimited callback functions (for memory reasons!)
1458 * no matter how often _setupInlineCrypt() would be called. At some
1459 * point of amount they must be generic re-useable.
1461 * - the code of _setupInlineCrypt() it self,
1462 * and the generated callback code,
1463 * must be, in following order:
1464 * - 100% safe
1465 * - 100% compatible to encrypt()/decrypt()
1466 * - using only php5+ features/lang-constructs/php-extensions if
1467 * compatibility (down to php4) or fallback is provided
1468 * - readable/maintainable/understandable/commented and... not-cryptic-styled-code :-)
1469 * - >= 10% faster than encrypt()/decrypt() [which is, by the way,
1470 * the reason for the existence of _setupInlineCrypt() :-)]
1471 * - memory-nice
1472 * - short (as good as possible)
1474 * Note: - _setupInlineCrypt() is using _createInlineCryptFunction() to create the full callback function code.
1475 * - In case of using inline crypting, _setupInlineCrypt() must extend by the child Crypt_* class.
1476 * - The following variable names are reserved:
1477 * - $_* (all variable names prefixed with an underscore)
1478 * - $self (object reference to it self. Do not use $this, but $self instead)
1479 * - $in (the content of $in has to en/decrypt by the generated code)
1480 * - The callback function should not use the 'return' statement, but en/decrypt'ing the content of $in only
1483 * @see Crypt_Base::_setup()
1484 * @see Crypt_Base::_createInlineCryptFunction()
1485 * @see Crypt_Base::encrypt()
1486 * @see Crypt_Base::decrypt()
1487 * @access private
1489 function _setupInlineCrypt()
1491 // If a Crypt_* class providing inline crypting it must extend _setupInlineCrypt()
1493 // If, for any reason, an extending Crypt_Base() Crypt_* class
1494 // not using inline crypting then it must be ensured that: $this->use_inline_crypt = false
1495 // ie in the class var declaration of $use_inline_crypt in general for the Crypt_* class,
1496 // in the constructor at object instance-time
1497 // or, if it's runtime-specific, at runtime
1499 $this->use_inline_crypt = false;
1503 * Creates the performance-optimized function for en/decrypt()
1505 * Internally for phpseclib developers:
1507 * _createInlineCryptFunction():
1509 * - merge the $cipher_code [setup'ed by _setupInlineCrypt()]
1510 * with the current [$this->]mode of operation code
1512 * - create the $inline function, which called by encrypt() / decrypt()
1513 * as its replacement to speed up the en/decryption operations.
1515 * - return the name of the created $inline callback function
1517 * - used to speed up en/decryption
1521 * The main reason why can speed up things [up to 50%] this way are:
1523 * - using variables more effective then regular.
1524 * (ie no use of expensive arrays but integers $k_0, $k_1 ...
1525 * or even, for example, the pure $key[] values hardcoded)
1527 * - avoiding 1000's of function calls of ie _encryptBlock()
1528 * but inlining the crypt operations.
1529 * in the mode of operation for() loop.
1531 * - full loop unroll the (sometimes key-dependent) rounds
1532 * avoiding this way ++$i counters and runtime-if's etc...
1534 * The basic code architectur of the generated $inline en/decrypt()
1535 * lambda function, in pseudo php, is:
1537 * <code>
1538 * +----------------------------------------------------------------------------------------------+
1539 * | callback $inline = create_function: |
1540 * | lambda_function_0001_crypt_ECB($action, $text) |
1541 * | { |
1542 * | INSERT PHP CODE OF: |
1543 * | $cipher_code['init_crypt']; // general init code. |
1544 * | // ie: $sbox'es declarations used for |
1545 * | // encrypt and decrypt'ing. |
1546 * | |
1547 * | switch ($action) { |
1548 * | case 'encrypt': |
1549 * | INSERT PHP CODE OF: |
1550 * | $cipher_code['init_encrypt']; // encrypt sepcific init code. |
1551 * | ie: specified $key or $box |
1552 * | declarations for encrypt'ing. |
1553 * | |
1554 * | foreach ($ciphertext) { |
1555 * | $in = $block_size of $ciphertext; |
1556 * | |
1557 * | INSERT PHP CODE OF: |
1558 * | $cipher_code['encrypt_block']; // encrypt's (string) $in, which is always: |
1559 * | // strlen($in) == $this->block_size |
1560 * | // here comes the cipher algorithm in action |
1561 * | // for encryption. |
1562 * | // $cipher_code['encrypt_block'] has to |
1563 * | // encrypt the content of the $in variable |
1564 * | |
1565 * | $plaintext .= $in; |
1566 * | } |
1567 * | return $plaintext; |
1568 * | |
1569 * | case 'decrypt': |
1570 * | INSERT PHP CODE OF: |
1571 * | $cipher_code['init_decrypt']; // decrypt sepcific init code |
1572 * | ie: specified $key or $box |
1573 * | declarations for decrypt'ing. |
1574 * | foreach ($plaintext) { |
1575 * | $in = $block_size of $plaintext; |
1576 * | |
1577 * | INSERT PHP CODE OF: |
1578 * | $cipher_code['decrypt_block']; // decrypt's (string) $in, which is always |
1579 * | // strlen($in) == $this->block_size |
1580 * | // here comes the cipher algorithm in action |
1581 * | // for decryption. |
1582 * | // $cipher_code['decrypt_block'] has to |
1583 * | // decrypt the content of the $in variable |
1584 * | $ciphertext .= $in; |
1585 * | } |
1586 * | return $ciphertext; |
1587 * | } |
1588 * | } |
1589 * +----------------------------------------------------------------------------------------------+
1590 * </code>
1592 * See also the Crypt_*::_setupInlineCrypt()'s for
1593 * productive inline $cipher_code's how they works.
1595 * Structure of:
1596 * <code>
1597 * $cipher_code = array(
1598 * 'init_crypt' => (string) '', // optional
1599 * 'init_encrypt' => (string) '', // optional
1600 * 'init_decrypt' => (string) '', // optional
1601 * 'encrypt_block' => (string) '', // required
1602 * 'decrypt_block' => (string) '' // required
1603 * );
1604 * </code>
1606 * @see Crypt_Base::_setupInlineCrypt()
1607 * @see Crypt_Base::encrypt()
1608 * @see Crypt_Base::decrypt()
1609 * @param Array $cipher_code
1610 * @access private
1611 * @return String (the name of the created callback function)
1613 function _createInlineCryptFunction($cipher_code)
1615 $block_size = $this->block_size;
1617 // optional
1618 $init_crypt = isset($cipher_code['init_crypt']) ? $cipher_code['init_crypt'] : '';
1619 $init_encrypt = isset($cipher_code['init_encrypt']) ? $cipher_code['init_encrypt'] : '';
1620 $init_decrypt = isset($cipher_code['init_decrypt']) ? $cipher_code['init_decrypt'] : '';
1621 // required
1622 $encrypt_block = $cipher_code['encrypt_block'];
1623 $decrypt_block = $cipher_code['decrypt_block'];
1625 // Generating mode of operation inline code,
1626 // merged with the $cipher_code algorithm
1627 // for encrypt- and decryption.
1628 switch ($this->mode) {
1629 case CRYPT_MODE_ECB:
1630 $encrypt = $init_encrypt . '
1631 $_ciphertext = "";
1632 $_text = $self->_pad($_text);
1633 $_plaintext_len = strlen($_text);
1635 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1636 $in = substr($_text, $_i, '.$block_size.');
1637 '.$encrypt_block.'
1638 $_ciphertext.= $in;
1641 return $_ciphertext;
1644 $decrypt = $init_decrypt . '
1645 $_plaintext = "";
1646 $_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0));
1647 $_ciphertext_len = strlen($_text);
1649 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1650 $in = substr($_text, $_i, '.$block_size.');
1651 '.$decrypt_block.'
1652 $_plaintext.= $in;
1655 return $self->_unpad($_plaintext);
1657 break;
1658 case CRYPT_MODE_CTR:
1659 $encrypt = $init_encrypt . '
1660 $_ciphertext = "";
1661 $_plaintext_len = strlen($_text);
1662 $_xor = $self->encryptIV;
1663 $_buffer = &$self->enbuffer;
1665 if (strlen($_buffer["encrypted"])) {
1666 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1667 $_block = substr($_text, $_i, '.$block_size.');
1668 if (strlen($_block) > strlen($_buffer["encrypted"])) {
1669 $in = $self->_generateXor($_xor, '.$block_size.');
1670 '.$encrypt_block.'
1671 $_buffer["encrypted"].= $in;
1673 $_key = $self->_stringShift($_buffer["encrypted"], '.$block_size.');
1674 $_ciphertext.= $_block ^ $_key;
1676 } else {
1677 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1678 $_block = substr($_text, $_i, '.$block_size.');
1679 $in = $self->_generateXor($_xor, '.$block_size.');
1680 '.$encrypt_block.'
1681 $_key = $in;
1682 $_ciphertext.= $_block ^ $_key;
1685 if ($self->continuousBuffer) {
1686 $self->encryptIV = $_xor;
1687 if ($_start = $_plaintext_len % '.$block_size.') {
1688 $_buffer["encrypted"] = substr($_key, $_start) . $_buffer["encrypted"];
1692 return $_ciphertext;
1695 $decrypt = $init_encrypt . '
1696 $_plaintext = "";
1697 $_ciphertext_len = strlen($_text);
1698 $_xor = $self->decryptIV;
1699 $_buffer = &$self->debuffer;
1701 if (strlen($_buffer["ciphertext"])) {
1702 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1703 $_block = substr($_text, $_i, '.$block_size.');
1704 if (strlen($_block) > strlen($_buffer["ciphertext"])) {
1705 $in = $self->_generateXor($_xor, '.$block_size.');
1706 '.$encrypt_block.'
1707 $_buffer["ciphertext"].= $in;
1709 $_key = $self->_stringShift($_buffer["ciphertext"], '.$block_size.');
1710 $_plaintext.= $_block ^ $_key;
1712 } else {
1713 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1714 $_block = substr($_text, $_i, '.$block_size.');
1715 $in = $self->_generateXor($_xor, '.$block_size.');
1716 '.$encrypt_block.'
1717 $_key = $in;
1718 $_plaintext.= $_block ^ $_key;
1721 if ($self->continuousBuffer) {
1722 $self->decryptIV = $_xor;
1723 if ($_start = $_ciphertext_len % '.$block_size.') {
1724 $_buffer["ciphertext"] = substr($_key, $_start) . $_buffer["ciphertext"];
1728 return $_plaintext;
1730 break;
1731 case CRYPT_MODE_CFB:
1732 $encrypt = $init_encrypt . '
1733 $_ciphertext = "";
1734 $_buffer = &$self->enbuffer;
1736 if ($self->continuousBuffer) {
1737 $_iv = &$self->encryptIV;
1738 $_pos = &$_buffer["pos"];
1739 } else {
1740 $_iv = $self->encryptIV;
1741 $_pos = 0;
1743 $_len = strlen($_text);
1744 $_i = 0;
1745 if ($_pos) {
1746 $_orig_pos = $_pos;
1747 $_max = '.$block_size.' - $_pos;
1748 if ($_len >= $_max) {
1749 $_i = $_max;
1750 $_len-= $_max;
1751 $_pos = 0;
1752 } else {
1753 $_i = $_len;
1754 $_pos+= $_len;
1755 $_len = 0;
1757 $_ciphertext = substr($_iv, $_orig_pos) ^ $_text;
1758 $_iv = substr_replace($_iv, $_ciphertext, $_orig_pos, $_i);
1760 while ($_len >= '.$block_size.') {
1761 $in = $_iv;
1762 '.$encrypt_block.';
1763 $_iv = $in ^ substr($_text, $_i, '.$block_size.');
1764 $_ciphertext.= $_iv;
1765 $_len-= '.$block_size.';
1766 $_i+= '.$block_size.';
1768 if ($_len) {
1769 $in = $_iv;
1770 '.$encrypt_block.'
1771 $_iv = $in;
1772 $_block = $_iv ^ substr($_text, $_i);
1773 $_iv = substr_replace($_iv, $_block, 0, $_len);
1774 $_ciphertext.= $_block;
1775 $_pos = $_len;
1777 return $_ciphertext;
1780 $decrypt = $init_encrypt . '
1781 $_plaintext = "";
1782 $_buffer = &$self->debuffer;
1784 if ($self->continuousBuffer) {
1785 $_iv = &$self->decryptIV;
1786 $_pos = &$_buffer["pos"];
1787 } else {
1788 $_iv = $self->decryptIV;
1789 $_pos = 0;
1791 $_len = strlen($_text);
1792 $_i = 0;
1793 if ($_pos) {
1794 $_orig_pos = $_pos;
1795 $_max = '.$block_size.' - $_pos;
1796 if ($_len >= $_max) {
1797 $_i = $_max;
1798 $_len-= $_max;
1799 $_pos = 0;
1800 } else {
1801 $_i = $_len;
1802 $_pos+= $_len;
1803 $_len = 0;
1805 $_plaintext = substr($_iv, $_orig_pos) ^ $_text;
1806 $_iv = substr_replace($_iv, substr($_text, 0, $_i), $_orig_pos, $_i);
1808 while ($_len >= '.$block_size.') {
1809 $in = $_iv;
1810 '.$encrypt_block.'
1811 $_iv = $in;
1812 $cb = substr($_text, $_i, '.$block_size.');
1813 $_plaintext.= $_iv ^ $cb;
1814 $_iv = $cb;
1815 $_len-= '.$block_size.';
1816 $_i+= '.$block_size.';
1818 if ($_len) {
1819 $in = $_iv;
1820 '.$encrypt_block.'
1821 $_iv = $in;
1822 $_plaintext.= $_iv ^ substr($_text, $_i);
1823 $_iv = substr_replace($_iv, substr($_text, $_i), 0, $_len);
1824 $_pos = $_len;
1827 return $_plaintext;
1829 break;
1830 case CRYPT_MODE_OFB:
1831 $encrypt = $init_encrypt . '
1832 $_ciphertext = "";
1833 $_plaintext_len = strlen($_text);
1834 $_xor = $self->encryptIV;
1835 $_buffer = &$self->enbuffer;
1837 if (strlen($_buffer["xor"])) {
1838 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1839 $_block = substr($_text, $_i, '.$block_size.');
1840 if (strlen($_block) > strlen($_buffer["xor"])) {
1841 $in = $_xor;
1842 '.$encrypt_block.'
1843 $_xor = $in;
1844 $_buffer["xor"].= $_xor;
1846 $_key = $self->_stringShift($_buffer["xor"], '.$block_size.');
1847 $_ciphertext.= $_block ^ $_key;
1849 } else {
1850 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1851 $in = $_xor;
1852 '.$encrypt_block.'
1853 $_xor = $in;
1854 $_ciphertext.= substr($_text, $_i, '.$block_size.') ^ $_xor;
1856 $_key = $_xor;
1858 if ($self->continuousBuffer) {
1859 $self->encryptIV = $_xor;
1860 if ($_start = $_plaintext_len % '.$block_size.') {
1861 $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
1864 return $_ciphertext;
1867 $decrypt = $init_encrypt . '
1868 $_plaintext = "";
1869 $_ciphertext_len = strlen($_text);
1870 $_xor = $self->decryptIV;
1871 $_buffer = &$self->debuffer;
1873 if (strlen($_buffer["xor"])) {
1874 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1875 $_block = substr($_text, $_i, '.$block_size.');
1876 if (strlen($_block) > strlen($_buffer["xor"])) {
1877 $in = $_xor;
1878 '.$encrypt_block.'
1879 $_xor = $in;
1880 $_buffer["xor"].= $_xor;
1882 $_key = $self->_stringShift($_buffer["xor"], '.$block_size.');
1883 $_plaintext.= $_block ^ $_key;
1885 } else {
1886 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1887 $in = $_xor;
1888 '.$encrypt_block.'
1889 $_xor = $in;
1890 $_plaintext.= substr($_text, $_i, '.$block_size.') ^ $_xor;
1892 $_key = $_xor;
1894 if ($self->continuousBuffer) {
1895 $self->decryptIV = $_xor;
1896 if ($_start = $_ciphertext_len % '.$block_size.') {
1897 $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
1900 return $_plaintext;
1902 break;
1903 case CRYPT_MODE_STREAM:
1904 $encrypt = $init_encrypt . '
1905 $_ciphertext = "";
1906 '.$encrypt_block.'
1907 return $_ciphertext;
1909 $decrypt = $init_decrypt . '
1910 $_plaintext = "";
1911 '.$decrypt_block.'
1912 return $_plaintext;
1914 break;
1915 // case CRYPT_MODE_CBC:
1916 default:
1917 $encrypt = $init_encrypt . '
1918 $_ciphertext = "";
1919 $_text = $self->_pad($_text);
1920 $_plaintext_len = strlen($_text);
1922 $in = $self->encryptIV;
1924 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1925 $in = substr($_text, $_i, '.$block_size.') ^ $in;
1926 '.$encrypt_block.'
1927 $_ciphertext.= $in;
1930 if ($self->continuousBuffer) {
1931 $self->encryptIV = $in;
1934 return $_ciphertext;
1937 $decrypt = $init_decrypt . '
1938 $_plaintext = "";
1939 $_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0));
1940 $_ciphertext_len = strlen($_text);
1942 $_iv = $self->decryptIV;
1944 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1945 $in = $_block = substr($_text, $_i, '.$block_size.');
1946 '.$decrypt_block.'
1947 $_plaintext.= $in ^ $_iv;
1948 $_iv = $_block;
1951 if ($self->continuousBuffer) {
1952 $self->decryptIV = $_iv;
1955 return $self->_unpad($_plaintext);
1957 break;
1960 // Create the $inline function and return its name as string. Ready to run!
1961 return create_function('$_action, &$self, $_text', $init_crypt . 'if ($_action == "encrypt") { ' . $encrypt . ' } else { ' . $decrypt . ' }');
1965 * Holds the lambda_functions table (classwide)
1967 * Each name of the lambda function, created from
1968 * _setupInlineCrypt() && _createInlineCryptFunction()
1969 * is stored, classwide (!), here for reusing.
1971 * The string-based index of $function is a classwide
1972 * uniqe value representing, at least, the $mode of
1973 * operation (or more... depends of the optimizing level)
1974 * for which $mode the lambda function was created.
1976 * @access private
1977 * @return &Array
1979 function &_getLambdaFunctions()
1981 static $functions = array();
1982 return $functions;