4 * Base Class for all Crypt_* cipher classes
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:
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
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
57 * @see Crypt_Base::encrypt()
58 * @see Crypt_Base::decrypt()
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);
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);
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);
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);
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);
93 * Encrypt / decrypt using streaming mode.
96 define('CRYPT_MODE_STREAM', 5);
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);
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>
124 * The Encryption Mode
126 * @see Crypt_Base::Crypt_Base()
133 * The Block Length of the block cipher
138 var $block_size = 16;
143 * @see Crypt_Base::setKey()
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()
159 * A "sliding" Initialization Vector
161 * @see Crypt_Base::enableContinuousBuffer()
162 * @see Crypt_Base::_clearBuffers()
169 * A "sliding" Initialization Vector
171 * @see Crypt_Base::enableContinuousBuffer()
172 * @see Crypt_Base::_clearBuffers()
179 * Continuous Buffer status
181 * @see Crypt_Base::enableContinuousBuffer()
185 var $continuousBuffer = false;
188 * Encryption buffer for CTR, OFB and CFB modes
190 * @see Crypt_Base::encrypt()
191 * @see Crypt_Base::_clearBuffers()
198 * Decryption buffer for CTR, OFB and CFB modes
200 * @see Crypt_Base::decrypt()
201 * @see Crypt_Base::_clearBuffers()
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()
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()
232 * Does the enmcrypt resource need to be (re)initialized?
234 * @see Crypt_Twofish::setKey()
235 * @see Crypt_Twofish::setIV()
239 var $enchanged = true;
242 * Does the demcrypt resource need to be (re)initialized?
244 * @see Crypt_Twofish::setKey()
245 * @see Crypt_Twofish::setIV()
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()
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()
290 var $cfb_init_len = 600;
293 * Does internal cipher state need to be (re)initialized?
297 * @see disableContinuousBuffer()
306 * @see Crypt_Base::enablePadding()
313 * Is the mode one that is paddable?
315 * @see Crypt_Base::Crypt_Base()
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()
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()
353 var $cipher_name_mcrypt;
356 * The default password key_size used by setPassword()
358 * @see Crypt_Base::setPassword()
362 var $password_key_size = 32;
365 * The default salt used by setPassword()
367 * @see Crypt_Base::setPassword()
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
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()
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
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
420 var $use_inline_crypt;
423 * Default Constructor.
425 * Determines whether or not the mcrypt extension should be used.
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
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)) {
453 case extension_loaded('mcrypt') && in_array($this->cipher_name_mcrypt
, mcrypt_list_algorithms()):
454 define($const_crypt_mode, CRYPT_MODE_MCRYPT
);
457 define($const_crypt_mode, CRYPT_MODE_INTERNAL
);
461 // Determining which internal $engine should be used.
462 // The fastes possible first.
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
;
467 case constant($const_crypt_mode) == CRYPT_MODE_MCRYPT
:
468 $this->engine
= CRYPT_MODE_MCRYPT
;
471 $this->engine
= CRYPT_MODE_INTERNAL
;
474 // $mode dependent settings
477 $this->paddable
= true;
483 case CRYPT_MODE_STREAM
:
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
504 * Note: Could, but not must, extend by the child Crypt_* class
511 if ($this->mode
== CRYPT_MODE_ECB
) {
516 $this->changed
= true;
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
534 function setKey($key)
537 $this->changed
= true;
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
556 function setPassword($password, $method = 'pbkdf2')
562 $func_args = func_get_args();
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;
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
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';
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);
597 $key = substr($key, 0, $dkLen);
600 $key = hash_pbkdf2($hash, $password, $salt, $count, $dkLen, true);
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
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
621 * Note: Could, but not must, extend by the child Crypt_* class
623 * @see Crypt_Base::decrypt()
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);
652 $max = $block_size - $pos;
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);
676 while ($len >= $block_size) {
677 $iv = mcrypt_generic($this->ecb
, $iv) ^
substr($plaintext, $i, $block_size);
686 $iv = mcrypt_generic($this->ecb
, $iv);
687 $block = $iv ^
substr($plaintext, -$len);
688 $iv = substr_replace($iv, $block, 0, $len);
689 $ciphertext.= $block;
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
);
709 if ($this->changed
) {
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
;
724 switch ($this->mode
) {
726 for ($i = 0; $i < strlen($plaintext); $i+
=$block_size) {
727 $ciphertext.= $this->_encryptBlock(substr($plaintext, $i, $block_size));
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);
736 $ciphertext.= $block;
738 if ($this->continuousBuffer
) {
739 $this->encryptIV
= $xor;
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;
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'];
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'];
774 $iv = $this->encryptIV
;
777 $len = strlen($plaintext);
781 $max = $block_size - $pos;
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);
802 $iv = $this->_encryptBlock($iv);
803 $block = $iv ^
substr($plaintext, $i);
804 $iv = substr_replace($iv, $block, 0, $len);
805 $ciphertext.= $block;
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;
822 for ($i = 0; $i < strlen($plaintext); $i+
=$block_size) {
823 $xor = $this->_encryptBlock($xor);
824 $ciphertext.= substr($plaintext, $i, $block_size) ^
$xor;
828 if ($this->continuousBuffer
) {
829 $this->encryptIV
= $xor;
830 if ($start = strlen($plaintext) %
$block_size) {
831 $buffer['xor'] = substr($key, $start) . $buffer['xor'];
835 case CRYPT_MODE_STREAM
:
836 $ciphertext = $this->_encryptBlock($plaintext);
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
849 * Note: Could, but not must, extend by the child Crypt_* class
851 * @see Crypt_Base::encrypt()
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);
877 $max = $block_size - $pos;
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);
898 $iv = mcrypt_generic($this->ecb
, $iv);
899 $plaintext.= $iv ^
substr($ciphertext, -$len);
900 $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len);
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
) {
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
;
939 switch ($this->mode
) {
941 for ($i = 0; $i < strlen($ciphertext); $i+
=$block_size) {
942 $plaintext.= $this->_decryptBlock(substr($ciphertext, $i, $block_size));
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;
952 if ($this->continuousBuffer
) {
953 $this->decryptIV
= $xor;
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;
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'];
982 if ($this->continuousBuffer
) {
983 $iv = &$this->decryptIV
;
984 $pos = &$buffer['pos'];
986 $iv = $this->decryptIV
;
989 $len = strlen($ciphertext);
993 $max = $block_size - $pos;
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;
1016 $iv = $this->_encryptBlock($iv);
1017 $plaintext.= $iv ^
substr($ciphertext, $i);
1018 $iv = substr_replace($iv, substr($ciphertext, $i), 0, $len);
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;
1035 for ($i = 0; $i < strlen($ciphertext); $i+
=$block_size) {
1036 $xor = $this->_encryptBlock($xor);
1037 $plaintext.= substr($ciphertext, $i, $block_size) ^
$xor;
1041 if ($this->continuousBuffer
) {
1042 $this->decryptIV
= $xor;
1043 if ($start = strlen($ciphertext) %
$block_size) {
1044 $buffer['xor'] = substr($key, $start) . $buffer['xor'];
1048 case CRYPT_MODE_STREAM
:
1049 $plaintext = $this->_decryptBlock($ciphertext);
1052 return $this->paddable ?
$this->_unpad($plaintext) : $plaintext;
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()
1070 function enablePadding()
1072 $this->padding
= true;
1076 * Do not pad packets.
1078 * @see Crypt_Base::enablePadding()
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:
1093 * echo $rijndael->encrypt(substr($plaintext, 0, 16));
1094 * echo $rijndael->encrypt(substr($plaintext, 16, 16));
1097 * echo $rijndael->encrypt($plaintext);
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:
1104 * $rijndael->encrypt(substr($plaintext, 0, 16));
1105 * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
1108 * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
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()
1125 function enableContinuousBuffer()
1127 if ($this->mode
== CRYPT_MODE_ECB
) {
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()
1144 function disableContinuousBuffer()
1146 if ($this->mode
== CRYPT_MODE_ECB
) {
1149 if (!$this->continuousBuffer
) {
1153 $this->continuousBuffer
= false;
1154 $this->changed
= true;
1160 * Note: Must extend by the child Crypt_* class
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
);
1174 * Note: Must extend by the child Crypt_* class
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()
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:
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
1223 * @see disableContinuousBuffer()
1228 $this->_clearBuffers();
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:
1249 * - disableContinuousBuffer()
1251 * - First run of encrypt() / decrypt()
1254 * Note: Could, but not must, extend by the child Crypt_* class
1258 * @see disableContinuousBuffer()
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
));
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
1308 function _pad($text)
1310 $length = strlen($text);
1312 if (!$this->padding
) {
1313 if ($length %
$this->block_size
== 0) {
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));
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
1337 function _unpad($text)
1339 if (!$this->padding
) {
1343 $length = ord($text[strlen($text) - 1]);
1345 if (!$length ||
$length > $this->block_size
) {
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
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");
1376 * Inspired by array_shift
1378 * @param String $string
1379 * @param optional Integer $index
1383 function _stringShift(&$string, $index = 1)
1385 $substr = substr($string, 0, $index);
1386 $string = substr($string, $index);
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()
1399 * @param Integer $length
1401 * @return String $xor
1403 function _generateXor(&$iv, $length)
1406 $block_size = $this->block_size
;
1407 $num_blocks = floor(($length +
($block_size - 1)) / $block_size);
1408 for ($i = 0; $i < $num_blocks; $i++
) {
1410 for ($j = 4; $j <= $block_size; $j+
= 4) {
1411 $temp = substr($iv, -$j, 4);
1413 case "\xFF\xFF\xFF\xFF":
1414 $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4);
1416 case "\x7F\xFF\xFF\xFF":
1417 $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4);
1420 extract(unpack('Ncount', $temp));
1421 $iv = substr_replace($iv, pack('N', $count +
1), -$j, 4);
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:
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() :-)]
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()
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:
1538 * +----------------------------------------------------------------------------------------------+
1539 * | callback $inline = create_function: |
1540 * | lambda_function_0001_crypt_ECB($action, $text) |
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. |
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. |
1554 * | foreach ($ciphertext) { |
1555 * | $in = $block_size of $ciphertext; |
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 |
1565 * | $plaintext .= $in; |
1567 * | return $plaintext; |
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; |
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; |
1586 * | return $ciphertext; |
1589 * +----------------------------------------------------------------------------------------------+
1592 * See also the Crypt_*::_setupInlineCrypt()'s for
1593 * productive inline $cipher_code's how they works.
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
1606 * @see Crypt_Base::_setupInlineCrypt()
1607 * @see Crypt_Base::encrypt()
1608 * @see Crypt_Base::decrypt()
1609 * @param Array $cipher_code
1611 * @return String (the name of the created callback function)
1613 function _createInlineCryptFunction($cipher_code)
1615 $block_size = $this->block_size
;
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'] : '';
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 . '
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.');
1641 return $_ciphertext;
1644 $decrypt = $init_decrypt . '
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.');
1655 return $self->_unpad($_plaintext);
1658 case CRYPT_MODE_CTR
:
1659 $encrypt = $init_encrypt . '
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.');
1671 $_buffer["encrypted"].= $in;
1673 $_key = $self->_stringShift($_buffer["encrypted"], '.$block_size.');
1674 $_ciphertext.= $_block ^ $_key;
1677 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1678 $_block = substr($_text, $_i, '.$block_size.');
1679 $in = $self->_generateXor($_xor, '.$block_size.');
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 . '
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.');
1707 $_buffer["ciphertext"].= $in;
1709 $_key = $self->_stringShift($_buffer["ciphertext"], '.$block_size.');
1710 $_plaintext.= $_block ^ $_key;
1713 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1714 $_block = substr($_text, $_i, '.$block_size.');
1715 $in = $self->_generateXor($_xor, '.$block_size.');
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"];
1731 case CRYPT_MODE_CFB
:
1732 $encrypt = $init_encrypt . '
1734 $_buffer = &$self->enbuffer;
1736 if ($self->continuousBuffer) {
1737 $_iv = &$self->encryptIV;
1738 $_pos = &$_buffer["pos"];
1740 $_iv = $self->encryptIV;
1743 $_len = strlen($_text);
1747 $_max = '.$block_size.' - $_pos;
1748 if ($_len >= $_max) {
1757 $_ciphertext = substr($_iv, $_orig_pos) ^ $_text;
1758 $_iv = substr_replace($_iv, $_ciphertext, $_orig_pos, $_i);
1760 while ($_len >= '.$block_size.') {
1763 $_iv = $in ^ substr($_text, $_i, '.$block_size.');
1764 $_ciphertext.= $_iv;
1765 $_len-= '.$block_size.';
1766 $_i+= '.$block_size.';
1772 $_block = $_iv ^ substr($_text, $_i);
1773 $_iv = substr_replace($_iv, $_block, 0, $_len);
1774 $_ciphertext.= $_block;
1777 return $_ciphertext;
1780 $decrypt = $init_encrypt . '
1782 $_buffer = &$self->debuffer;
1784 if ($self->continuousBuffer) {
1785 $_iv = &$self->decryptIV;
1786 $_pos = &$_buffer["pos"];
1788 $_iv = $self->decryptIV;
1791 $_len = strlen($_text);
1795 $_max = '.$block_size.' - $_pos;
1796 if ($_len >= $_max) {
1805 $_plaintext = substr($_iv, $_orig_pos) ^ $_text;
1806 $_iv = substr_replace($_iv, substr($_text, 0, $_i), $_orig_pos, $_i);
1808 while ($_len >= '.$block_size.') {
1812 $cb = substr($_text, $_i, '.$block_size.');
1813 $_plaintext.= $_iv ^ $cb;
1815 $_len-= '.$block_size.';
1816 $_i+= '.$block_size.';
1822 $_plaintext.= $_iv ^ substr($_text, $_i);
1823 $_iv = substr_replace($_iv, substr($_text, $_i), 0, $_len);
1830 case CRYPT_MODE_OFB
:
1831 $encrypt = $init_encrypt . '
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"])) {
1844 $_buffer["xor"].= $_xor;
1846 $_key = $self->_stringShift($_buffer["xor"], '.$block_size.');
1847 $_ciphertext.= $_block ^ $_key;
1850 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1854 $_ciphertext.= substr($_text, $_i, '.$block_size.') ^ $_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 . '
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"])) {
1880 $_buffer["xor"].= $_xor;
1882 $_key = $self->_stringShift($_buffer["xor"], '.$block_size.');
1883 $_plaintext.= $_block ^ $_key;
1886 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1890 $_plaintext.= substr($_text, $_i, '.$block_size.') ^ $_xor;
1894 if ($self->continuousBuffer) {
1895 $self->decryptIV = $_xor;
1896 if ($_start = $_ciphertext_len % '.$block_size.') {
1897 $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
1903 case CRYPT_MODE_STREAM
:
1904 $encrypt = $init_encrypt . '
1907 return $_ciphertext;
1909 $decrypt = $init_decrypt . '
1915 // case CRYPT_MODE_CBC:
1917 $encrypt = $init_encrypt . '
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;
1930 if ($self->continuousBuffer) {
1931 $self->encryptIV = $in;
1934 return $_ciphertext;
1937 $decrypt = $init_decrypt . '
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.');
1947 $_plaintext.= $in ^ $_iv;
1951 if ($self->continuousBuffer) {
1952 $self->decryptIV = $_iv;
1955 return $self->_unpad($_plaintext);
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.
1979 function &_getLambdaFunctions()
1981 static $functions = array();