2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
5 * Base Class for all Crypt_* cipher classes
9 * Internally for phpseclib developers:
10 * If you plan to add a new cipher class, please note following rules:
12 * - The new Crypt_* cipher class should extend Crypt_Base
14 * - Following methods are then required to be overridden/overloaded:
22 * - All other methods are optional to be overridden/overloaded
24 * - Look at the source code of the current ciphers how they extend Crypt_Base
25 * and take one of them as a start up for the new cipher class.
27 * - Please read all the other comments/notes/hints here also for each class var/method
29 * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
30 * of this software and associated documentation files (the "Software"), to deal
31 * in the Software without restriction, including without limitation the rights
32 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
33 * copies of the Software, and to permit persons to whom the Software is
34 * furnished to do so, subject to the following conditions:
36 * The above copyright notice and this permission notice shall be included in
37 * all copies or substantial portions of the Software.
39 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
40 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
41 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
42 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
43 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
44 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
49 * @author Jim Wigginton <terrafrost@php.net>
50 * @author Hans-Juergen Petrich <petrich@tronic-media.com>
51 * @copyright MMVII Jim Wigginton
52 * @license http://www.opensource.org/licenses/mit-license.html MIT License
54 * @link http://phpseclib.sourceforge.net
59 * @see Crypt_Base::encrypt()
60 * @see Crypt_Base::decrypt()
63 * Encrypt / decrypt using the Counter mode.
65 * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
67 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
69 define('CRYPT_MODE_CTR', -1);
71 * Encrypt / decrypt using the Electronic Code Book mode.
73 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
75 define('CRYPT_MODE_ECB', 1);
77 * Encrypt / decrypt using the Code Book Chaining mode.
79 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
81 define('CRYPT_MODE_CBC', 2);
83 * Encrypt / decrypt using the Cipher Feedback mode.
85 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
87 define('CRYPT_MODE_CFB', 3);
89 * Encrypt / decrypt using the Output Feedback mode.
91 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
93 define('CRYPT_MODE_OFB', 4);
95 * Encrypt / decrypt using streaming mode.
98 define('CRYPT_MODE_STREAM', 5);
103 * @see Crypt_Base::Crypt_Base()
106 * Base value for the internal implementation $engine switch
108 define('CRYPT_MODE_INTERNAL', 1);
110 * Base value for the mcrypt implementation $engine switch
112 define('CRYPT_MODE_MCRYPT', 2);
116 * Base Class for all Crypt_* cipher classes
118 * @author Jim Wigginton <terrafrost@php.net>
119 * @author Hans-Juergen Petrich <petrich@tronic-media.com>
122 * @package Crypt_Base
126 * The Encryption Mode
128 * @see Crypt_Base::Crypt_Base()
135 * The Block Length of the block cipher
140 var $block_size = 16;
145 * @see Crypt_Base::setKey()
149 var $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
152 * The Initialization Vector
154 * @see Crypt_Base::setIV()
161 * A "sliding" Initialization Vector
163 * @see Crypt_Base::enableContinuousBuffer()
164 * @see Crypt_Base::_clearBuffers()
171 * A "sliding" Initialization Vector
173 * @see Crypt_Base::enableContinuousBuffer()
174 * @see Crypt_Base::_clearBuffers()
181 * Continuous Buffer status
183 * @see Crypt_Base::enableContinuousBuffer()
187 var $continuousBuffer = false;
190 * Encryption buffer for CTR, OFB and CFB modes
192 * @see Crypt_Base::encrypt()
193 * @see Crypt_Base::_clearBuffers()
200 * Decryption buffer for CTR, OFB and CFB modes
202 * @see Crypt_Base::decrypt()
203 * @see Crypt_Base::_clearBuffers()
210 * mcrypt resource for encryption
212 * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
213 * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
215 * @see Crypt_Base::encrypt()
222 * mcrypt resource for decryption
224 * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
225 * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
227 * @see Crypt_Base::decrypt()
234 * Does the enmcrypt resource need to be (re)initialized?
236 * @see Crypt_Twofish::setKey()
237 * @see Crypt_Twofish::setIV()
241 var $enchanged = true;
244 * Does the demcrypt resource need to be (re)initialized?
246 * @see Crypt_Twofish::setKey()
247 * @see Crypt_Twofish::setIV()
251 var $dechanged = true;
254 * mcrypt resource for CFB mode
256 * mcrypt's CFB mode, in (and only in) buffered context,
257 * is broken, so phpseclib implements the CFB mode by it self,
258 * even when the mcrypt php extension is available.
260 * In order to do the CFB-mode work (fast) phpseclib
261 * use a separate ECB-mode mcrypt resource.
263 * @link http://phpseclib.sourceforge.net/cfb-demo.phps
264 * @see Crypt_Base::encrypt()
265 * @see Crypt_Base::decrypt()
266 * @see Crypt_Base::_setupMcrypt()
273 * Optimizing value while CFB-encrypting
275 * Only relevant if $continuousBuffer enabled
276 * and $engine == CRYPT_MODE_MCRYPT
278 * It's faster to re-init $enmcrypt if
279 * $buffer bytes > $cfb_init_len than
280 * using the $ecb resource furthermore.
282 * This value depends of the choosen cipher
283 * and the time it would be needed for it's
284 * initialization [by mcrypt_generic_init()]
285 * which, typically, depends on the complexity
286 * on its internaly Key-expanding algorithm.
288 * @see Crypt_Base::encrypt()
292 var $cfb_init_len = 600;
295 * Does internal cipher state need to be (re)initialized?
299 * @see disableContinuousBuffer()
308 * @see Crypt_Base::enablePadding()
315 * Is the mode one that is paddable?
317 * @see Crypt_Base::Crypt_Base()
321 var $paddable = false;
324 * Holds which crypt engine internaly should be use,
325 * which will be determined automatically on __construct()
327 * Currently available $engines are:
328 * - CRYPT_MODE_MCRYPT (fast, php-extension: mcrypt, extension_loaded('mcrypt') required)
329 * - CRYPT_MODE_INTERNAL (slower, pure php-engine, no php-extension required)
331 * In the pipeline... maybe. But currently not available:
332 * - CRYPT_MODE_OPENSSL (very fast, php-extension: openssl, extension_loaded('openssl') required)
334 * If possible, CRYPT_MODE_MCRYPT will be used for each cipher.
335 * Otherwise CRYPT_MODE_INTERNAL
337 * @see Crypt_Base::encrypt()
338 * @see Crypt_Base::decrypt()
345 * The mcrypt specific name of the cipher
347 * Only used if $engine == CRYPT_MODE_MCRYPT
349 * @link http://www.php.net/mcrypt_module_open
350 * @link http://www.php.net/mcrypt_list_algorithms
351 * @see Crypt_Base::_setupMcrypt()
355 var $cipher_name_mcrypt;
358 * The default password key_size used by setPassword()
360 * @see Crypt_Base::setPassword()
364 var $password_key_size = 32;
367 * The default salt used by setPassword()
369 * @see Crypt_Base::setPassword()
373 var $password_default_salt = 'phpseclib/salt';
376 * The namespace used by the cipher for its constants.
378 * ie: AES.php is using CRYPT_AES_MODE_* for its constants
379 * so $const_namespace is AES
381 * DES.php is using CRYPT_DES_MODE_* for its constants
382 * so $const_namespace is DES... and so on
384 * All CRYPT_<$const_namespace>_MODE_* are aliases of
385 * the generic CRYPT_MODE_* constants, so both could be used
389 * $aes = new Crypt_AES(CRYPT_AES_MODE_CFB); // $aes will operate in cfb mode
390 * $aes = new Crypt_AES(CRYPT_MODE_CFB); // identical
392 * @see Crypt_Base::Crypt_Base()
396 var $const_namespace;
399 * The name of the performance-optimized callback function
401 * Used by encrypt() / decrypt()
402 * only if $engine == CRYPT_MODE_INTERNAL
404 * @see Crypt_Base::encrypt()
405 * @see Crypt_Base::decrypt()
406 * @see Crypt_Base::_setupInlineCrypt()
407 * @see Crypt_Base::$use_inline_crypt
414 * Holds whether performance-optimized $inline_crypt() can/should be used.
416 * @see Crypt_Base::encrypt()
417 * @see Crypt_Base::decrypt()
418 * @see Crypt_Base::inline_crypt
422 var $use_inline_crypt;
425 * Default Constructor.
427 * Determines whether or not the mcrypt extension should be used.
441 * (or the alias constants of the choosen cipher, for example for AES: CRYPT_AES_MODE_ECB or CRYPT_AES_MODE_CBC ...)
443 * If not explictly set, CRYPT_MODE_CBC will be used.
445 * @param optional Integer $mode
448 function Crypt_Base($mode = CRYPT_MODE_CBC)
450 $const_crypt_mode = 'CRYPT_' . $this->const_namespace . '_MODE';
452 // Determining the availibility of mcrypt support for the cipher
453 if (!defined($const_crypt_mode)) {
455 case extension_loaded('mcrypt') && in_array($this->cipher_name_mcrypt, mcrypt_list_algorithms()):
456 define($const_crypt_mode, CRYPT_MODE_MCRYPT);
459 define($const_crypt_mode, CRYPT_MODE_INTERNAL);
463 // Determining which internal $engine should be used.
464 // The fastes possible first.
466 case empty($this->cipher_name_mcrypt): // The cipher module has no mcrypt-engine support at all so we force CRYPT_MODE_INTERNAL
467 $this->engine = CRYPT_MODE_INTERNAL;
469 case constant($const_crypt_mode) == CRYPT_MODE_MCRYPT:
470 $this->engine = CRYPT_MODE_MCRYPT;
473 $this->engine = CRYPT_MODE_INTERNAL;
476 // $mode dependent settings
479 $this->paddable = true;
485 case CRYPT_MODE_STREAM:
490 $this->paddable = true;
491 $this->mode = CRYPT_MODE_CBC;
494 // Determining whether inline crypting can be used by the cipher
495 if ($this->use_inline_crypt !== false && function_exists('create_function')) {
496 $this->use_inline_crypt = true;
501 * Sets the initialization vector. (optional)
503 * SetIV is not required when CRYPT_MODE_ECB (or ie for AES: CRYPT_AES_MODE_ECB) is being used. If not explictly set, it'll be assumed
506 * Note: Could, but not must, extend by the child Crypt_* class
513 if ($this->mode == CRYPT_MODE_ECB) {
518 $this->changed = true;
524 * The min/max length(s) of the key depends on the cipher which is used.
525 * If the key not fits the length(s) of the cipher it will paded with null bytes
526 * up to the closest valid key length. If the key is more than max length,
527 * we trim the excess bits.
529 * If the key is not explicitly set, it'll be assumed to be all null bytes.
531 * Note: Could, but not must, extend by the child Crypt_* class
536 function setKey($key)
539 $this->changed = true;
545 * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows:
546 * {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2}:
547 * $hash, $salt, $count, $dkLen
549 * Where $hash (default = sha1) currently supports the following hashes: see: Crypt/Hash.php
551 * Note: Could, but not must, extend by the child Crypt_* class
553 * @see Crypt/Hash.php
554 * @param String $password
555 * @param optional String $method
558 function setPassword($password, $method = 'pbkdf2')
564 $func_args = func_get_args();
567 $hash = isset($func_args[2]) ? $func_args[2] : 'sha1';
569 // WPA and WPA2 use the SSID as the salt
570 $salt = isset($func_args[3]) ? $func_args[3] : $this->password_default_salt;
572 // RFC2898#section-4.2 uses 1,000 iterations by default
573 // WPA and WPA2 use 4,096.
574 $count = isset($func_args[4]) ? $func_args[4] : 1000;
577 $dkLen = isset($func_args[5]) ? $func_args[5] : $this->password_key_size;
579 // Determining if php[>=5.5.0]'s hash_pbkdf2() function avail- and useable
581 case !function_exists('hash_pbkdf2'):
582 case !function_exists('hash_algos'):
583 case !in_array($hash, hash_algos()):
584 if (!class_exists('Crypt_Hash')) {
585 require_once('Crypt/Hash.php');
588 while (strlen($key) < $dkLen) {
589 $hmac = new Crypt_Hash();
590 $hmac->setHash($hash);
591 $hmac->setKey($password);
592 $f = $u = $hmac->hash($salt . pack('N', $i++));
593 for ($j = 2; $j <= $count; ++$j) {
594 $u = $hmac->hash($u);
599 $key = substr($key, 0, $dkLen);
602 $key = hash_pbkdf2($hash, $password, $salt, $count, $dkLen, true);
610 * Encrypts a message.
612 * $plaintext will be padded with additional bytes such that it's length is a multiple of the block size. Other cipher
613 * implementations may or may not pad in the same manner. Other common approaches to padding and the reasons why it's
614 * necessary are discussed in the following
617 * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
619 * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does.
620 * strlen($plaintext) will still need to be a multiple of the block size, however, arbitrary values can be added to make it that
623 * Note: Could, but not must, extend by the child Crypt_* class
625 * @see Crypt_Base::decrypt()
627 * @param String $plaintext
628 * @return String $cipertext
630 function encrypt($plaintext)
632 if ($this->engine == CRYPT_MODE_MCRYPT) {
633 if ($this->changed) {
634 $this->_setupMcrypt();
635 $this->changed = false;
637 if ($this->enchanged) {
638 mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
639 $this->enchanged = false;
642 // re: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
643 // using mcrypt's default handing of CFB the above would output two different things. using phpseclib's
644 // rewritten CFB implementation the above outputs the same thing twice.
645 if ($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer) {
646 $block_size = $this->block_size;
647 $iv = &$this->encryptIV;
648 $pos = &$this->enbuffer['pos'];
649 $len = strlen($plaintext);
654 $max = $block_size - $pos;
664 $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
665 $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
666 $this->enbuffer['enmcrypt_init'] = true;
668 if ($len >= $block_size) {
669 if ($this->enbuffer['enmcrypt_init'] === false || $len > $this->cfb_init_len) {
670 if ($this->enbuffer['enmcrypt_init'] === true) {
671 mcrypt_generic_init($this->enmcrypt, $this->key, $iv);
672 $this->enbuffer['enmcrypt_init'] = false;
674 $ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % $block_size));
675 $iv = substr($ciphertext, -$block_size);
678 while ($len >= $block_size) {
679 $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, $block_size);
688 $iv = mcrypt_generic($this->ecb, $iv);
689 $block = $iv ^ substr($plaintext, -$len);
690 $iv = substr_replace($iv, $block, 0, $len);
691 $ciphertext.= $block;
698 if ($this->paddable) {
699 $plaintext = $this->_pad($plaintext);
702 $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
704 if (!$this->continuousBuffer) {
705 mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
711 if ($this->changed) {
713 $this->changed = false;
715 if ($this->use_inline_crypt) {
716 $inline = $this->inline_crypt;
717 return $inline('encrypt', $this, $plaintext);
719 if ($this->paddable) {
720 $plaintext = $this->_pad($plaintext);
723 $buffer = &$this->enbuffer;
724 $block_size = $this->block_size;
726 switch ($this->mode) {
728 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
729 $ciphertext.= $this->_encryptBlock(substr($plaintext, $i, $block_size));
733 $xor = $this->encryptIV;
734 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
735 $block = substr($plaintext, $i, $block_size);
736 $block = $this->_encryptBlock($block ^ $xor);
738 $ciphertext.= $block;
740 if ($this->continuousBuffer) {
741 $this->encryptIV = $xor;
745 $xor = $this->encryptIV;
746 if (strlen($buffer['encrypted'])) {
747 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
748 $block = substr($plaintext, $i, $block_size);
749 if (strlen($block) > strlen($buffer['encrypted'])) {
750 $buffer['encrypted'].= $this->_encryptBlock($this->_generateXor($xor, $block_size));
752 $key = $this->_stringShift($buffer['encrypted'], $block_size);
753 $ciphertext.= $block ^ $key;
756 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
757 $block = substr($plaintext, $i, $block_size);
758 $key = $this->_encryptBlock($this->_generateXor($xor, $block_size));
759 $ciphertext.= $block ^ $key;
762 if ($this->continuousBuffer) {
763 $this->encryptIV = $xor;
764 if ($start = strlen($plaintext) % $block_size) {
765 $buffer['encrypted'] = substr($key, $start) . $buffer['encrypted'];
770 // cfb loosely routines inspired by openssl's:
771 // {@link http://cvs.openssl.org/fileview?f=openssl/crypto/modes/cfb128.c&v=1.3.2.2.2.1}
772 if ($this->continuousBuffer) {
773 $iv = &$this->encryptIV;
774 $pos = &$buffer['pos'];
776 $iv = $this->encryptIV;
779 $len = strlen($plaintext);
783 $max = $block_size - $pos;
793 // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
794 $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
795 $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
797 while ($len >= $block_size) {
798 $iv = $this->_encryptBlock($iv) ^ substr($plaintext, $i, $block_size);
804 $iv = $this->_encryptBlock($iv);
805 $block = $iv ^ substr($plaintext, $i);
806 $iv = substr_replace($iv, $block, 0, $len);
807 $ciphertext.= $block;
812 $xor = $this->encryptIV;
813 if (strlen($buffer['xor'])) {
814 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
815 $block = substr($plaintext, $i, $block_size);
816 if (strlen($block) > strlen($buffer['xor'])) {
817 $xor = $this->_encryptBlock($xor);
818 $buffer['xor'].= $xor;
820 $key = $this->_stringShift($buffer['xor'], $block_size);
821 $ciphertext.= $block ^ $key;
824 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
825 $xor = $this->_encryptBlock($xor);
826 $ciphertext.= substr($plaintext, $i, $block_size) ^ $xor;
830 if ($this->continuousBuffer) {
831 $this->encryptIV = $xor;
832 if ($start = strlen($plaintext) % $block_size) {
833 $buffer['xor'] = substr($key, $start) . $buffer['xor'];
837 case CRYPT_MODE_STREAM:
838 $ciphertext = $this->_encryptBlock($plaintext);
846 * Decrypts a message.
848 * If strlen($ciphertext) is not a multiple of the block size, null bytes will be added to the end of the string until
851 * Note: Could, but not must, extend by the child Crypt_* class
853 * @see Crypt_Base::encrypt()
855 * @param String $ciphertext
856 * @return String $plaintext
858 function decrypt($ciphertext)
860 if ($this->engine == CRYPT_MODE_MCRYPT) {
861 $block_size = $this->block_size;
862 if ($this->changed) {
863 $this->_setupMcrypt();
864 $this->changed = false;
866 if ($this->dechanged) {
867 mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
868 $this->dechanged = false;
871 if ($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer) {
872 $iv = &$this->decryptIV;
873 $pos = &$this->debuffer['pos'];
874 $len = strlen($ciphertext);
879 $max = $block_size - $pos;
889 // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
890 $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
891 $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
893 if ($len >= $block_size) {
894 $cb = substr($ciphertext, $i, $len - $len % $block_size);
895 $plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
896 $iv = substr($cb, -$block_size);
900 $iv = mcrypt_generic($this->ecb, $iv);
901 $plaintext.= $iv ^ substr($ciphertext, -$len);
902 $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len);
909 if ($this->paddable) {
910 // we pad with chr(0) since that's what mcrypt_generic does. to quote from {@link http://www.php.net/function.mcrypt-generic}:
911 // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
912 $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($block_size - strlen($ciphertext) % $block_size) % $block_size, chr(0));
915 $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
917 if (!$this->continuousBuffer) {
918 mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
921 return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
924 if ($this->changed) {
926 $this->changed = false;
928 if ($this->use_inline_crypt) {
929 $inline = $this->inline_crypt;
930 return $inline('decrypt', $this, $ciphertext);
933 $block_size = $this->block_size;
934 if ($this->paddable) {
935 // we pad with chr(0) since that's what mcrypt_generic does [...]
936 $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($block_size - strlen($ciphertext) % $block_size) % $block_size, chr(0));
939 $buffer = &$this->debuffer;
941 switch ($this->mode) {
943 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
944 $plaintext.= $this->_decryptBlock(substr($ciphertext, $i, $block_size));
948 $xor = $this->decryptIV;
949 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
950 $block = substr($ciphertext, $i, $block_size);
951 $plaintext.= $this->_decryptBlock($block) ^ $xor;
954 if ($this->continuousBuffer) {
955 $this->decryptIV = $xor;
959 $xor = $this->decryptIV;
960 if (strlen($buffer['ciphertext'])) {
961 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
962 $block = substr($ciphertext, $i, $block_size);
963 if (strlen($block) > strlen($buffer['ciphertext'])) {
964 $buffer['ciphertext'].= $this->_encryptBlock($this->_generateXor($xor, $block_size));
966 $key = $this->_stringShift($buffer['ciphertext'], $block_size);
967 $plaintext.= $block ^ $key;
970 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
971 $block = substr($ciphertext, $i, $block_size);
972 $key = $this->_encryptBlock($this->_generateXor($xor, $block_size));
973 $plaintext.= $block ^ $key;
976 if ($this->continuousBuffer) {
977 $this->decryptIV = $xor;
978 if ($start = strlen($ciphertext) % $block_size) {
979 $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext'];
984 if ($this->continuousBuffer) {
985 $iv = &$this->decryptIV;
986 $pos = &$buffer['pos'];
988 $iv = $this->decryptIV;
991 $len = strlen($ciphertext);
995 $max = $block_size - $pos;
1005 // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
1006 $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
1007 $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
1009 while ($len >= $block_size) {
1010 $iv = $this->_encryptBlock($iv);
1011 $cb = substr($ciphertext, $i, $block_size);
1012 $plaintext.= $iv ^ $cb;
1018 $iv = $this->_encryptBlock($iv);
1019 $plaintext.= $iv ^ substr($ciphertext, $i);
1020 $iv = substr_replace($iv, substr($ciphertext, $i), 0, $len);
1024 case CRYPT_MODE_OFB:
1025 $xor = $this->decryptIV;
1026 if (strlen($buffer['xor'])) {
1027 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
1028 $block = substr($ciphertext, $i, $block_size);
1029 if (strlen($block) > strlen($buffer['xor'])) {
1030 $xor = $this->_encryptBlock($xor);
1031 $buffer['xor'].= $xor;
1033 $key = $this->_stringShift($buffer['xor'], $block_size);
1034 $plaintext.= $block ^ $key;
1037 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
1038 $xor = $this->_encryptBlock($xor);
1039 $plaintext.= substr($ciphertext, $i, $block_size) ^ $xor;
1043 if ($this->continuousBuffer) {
1044 $this->decryptIV = $xor;
1045 if ($start = strlen($ciphertext) % $block_size) {
1046 $buffer['xor'] = substr($key, $start) . $buffer['xor'];
1050 case CRYPT_MODE_STREAM:
1051 $plaintext = $this->_decryptBlock($ciphertext);
1054 return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
1060 * Block ciphers working by encrypting between their specified [$this->]block_size at a time
1061 * If you ever need to encrypt or decrypt something that isn't of the proper length, it becomes necessary to
1062 * pad the input so that it is of the proper length.
1064 * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH,
1065 * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping
1066 * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is
1067 * transmitted separately)
1069 * @see Crypt_Base::disablePadding()
1072 function enablePadding()
1074 $this->padding = true;
1078 * Do not pad packets.
1080 * @see Crypt_Base::enablePadding()
1083 function disablePadding()
1085 $this->padding = false;
1089 * Treat consecutive "packets" as if they are a continuous buffer.
1091 * Say you have a 32-byte plaintext $plaintext. Using the default behavior, the two following code snippets
1092 * will yield different outputs:
1095 * echo $rijndael->encrypt(substr($plaintext, 0, 16));
1096 * echo $rijndael->encrypt(substr($plaintext, 16, 16));
1099 * echo $rijndael->encrypt($plaintext);
1102 * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
1103 * another, as demonstrated with the following:
1106 * $rijndael->encrypt(substr($plaintext, 0, 16));
1107 * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
1110 * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
1113 * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
1114 * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
1115 * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
1117 * Put another way, when the continuous buffer is enabled, the state of the Crypt_*() object changes after each
1118 * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
1119 * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
1120 * however, they are also less intuitive and more likely to cause you problems.
1122 * Note: Could, but not must, extend by the child Crypt_* class
1124 * @see Crypt_Base::disableContinuousBuffer()
1127 function enableContinuousBuffer()
1129 if ($this->mode == CRYPT_MODE_ECB) {
1133 $this->continuousBuffer = true;
1137 * Treat consecutive packets as if they are a discontinuous buffer.
1139 * The default behavior.
1141 * Note: Could, but not must, extend by the child Crypt_* class
1143 * @see Crypt_Base::enableContinuousBuffer()
1146 function disableContinuousBuffer()
1148 if ($this->mode == CRYPT_MODE_ECB) {
1151 if (!$this->continuousBuffer) {
1155 $this->continuousBuffer = false;
1156 $this->changed = true;
1162 * Note: Must extend by the child Crypt_* class
1168 function _encryptBlock($in)
1170 user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
1176 * Note: Must extend by the child Crypt_* class
1182 function _decryptBlock($in)
1184 user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
1188 * Setup the key (expansion)
1190 * Only used if $engine == CRYPT_MODE_INTERNAL
1192 * Note: Must extend by the child Crypt_* class
1194 * @see Crypt_Base::_setup()
1197 function _setupKey()
1199 user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
1203 * Setup the CRYPT_MODE_INTERNAL $engine
1205 * (re)init, if necessary, the internal cipher $engine and flush all $buffers
1206 * Used (only) if $engine == CRYPT_MODE_INTERNAL
1208 * _setup() will be called each time if $changed === true
1209 * typically this happens when using one or more of following public methods:
1215 * - disableContinuousBuffer()
1217 * - First run of encrypt() / decrypt() with no init-settings
1219 * Internally: _setup() is called always before(!) en/decryption.
1221 * Note: Could, but not must, extend by the child Crypt_* class
1225 * @see disableContinuousBuffer()
1230 $this->_clearBuffers();
1233 if ($this->use_inline_crypt) {
1234 $this->_setupInlineCrypt();
1239 * Setup the CRYPT_MODE_MCRYPT $engine
1241 * (re)init, if necessary, the (ext)mcrypt resources and flush all $buffers
1242 * Used (only) if $engine = CRYPT_MODE_MCRYPT
1244 * _setupMcrypt() will be called each time if $changed === true
1245 * typically this happens when using one or more of following public methods:
1251 * - disableContinuousBuffer()
1253 * - First run of encrypt() / decrypt()
1256 * Note: Could, but not must, extend by the child Crypt_* class
1260 * @see disableContinuousBuffer()
1263 function _setupMcrypt()
1265 $this->_clearBuffers();
1266 $this->enchanged = $this->dechanged = true;
1268 if (!isset($this->enmcrypt)) {
1269 static $mcrypt_modes = array(
1270 CRYPT_MODE_CTR => 'ctr',
1271 CRYPT_MODE_ECB => MCRYPT_MODE_ECB,
1272 CRYPT_MODE_CBC => MCRYPT_MODE_CBC,
1273 CRYPT_MODE_CFB => 'ncfb',
1274 CRYPT_MODE_OFB => MCRYPT_MODE_NOFB,
1275 CRYPT_MODE_STREAM => MCRYPT_MODE_STREAM,
1278 $this->demcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
1279 $this->enmcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
1281 // we need the $ecb mcrypt resource (only) in MODE_CFB with enableContinuousBuffer()
1282 // to workaround mcrypt's broken ncfb implementation in buffered mode
1283 // see: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
1284 if ($this->mode == CRYPT_MODE_CFB) {
1285 $this->ecb = mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, '');
1288 } // else should mcrypt_generic_deinit be called?
1290 if ($this->mode == CRYPT_MODE_CFB) {
1291 mcrypt_generic_init($this->ecb, $this->key, str_repeat("\0", $this->block_size));
1298 * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize.
1299 * $this->block_size - (strlen($text) % $this->block_size) bytes are added, each of which is equal to
1300 * chr($this->block_size - (strlen($text) % $this->block_size)
1302 * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless
1303 * and padding will, hence forth, be enabled.
1305 * @see Crypt_Base::_unpad()
1306 * @param String $text
1310 function _pad($text)
1312 $length = strlen($text);
1314 if (!$this->padding) {
1315 if ($length % $this->block_size == 0) {
1318 user_error("The plaintext's length ($length) is not a multiple of the block size ({$this->block_size})");
1319 $this->padding = true;
1323 $pad = $this->block_size - ($length % $this->block_size);
1325 return str_pad($text, $length + $pad, chr($pad));
1331 * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong
1332 * and false will be returned.
1334 * @see Crypt_Base::_pad()
1335 * @param String $text
1339 function _unpad($text)
1341 if (!$this->padding) {
1345 $length = ord($text[strlen($text) - 1]);
1347 if (!$length || $length > $this->block_size) {
1351 return substr($text, 0, -$length);
1355 * Clears internal buffers
1357 * Clearing/resetting the internal buffers is done everytime
1358 * after disableContinuousBuffer() or on cipher $engine (re)init
1359 * ie after setKey() or setIV()
1361 * Note: Could, but not must, extend by the child Crypt_* class
1365 function _clearBuffers()
1367 $this->enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
1368 $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true);
1370 // mcrypt's handling of invalid's $iv:
1371 // $this->encryptIV = $this->decryptIV = strlen($this->iv) == $this->block_size ? $this->iv : str_repeat("\0", $this->block_size);
1372 $this->encryptIV = $this->decryptIV = str_pad(substr($this->iv, 0, $this->block_size), $this->block_size, "\0");
1378 * Inspired by array_shift
1380 * @param String $string
1381 * @param optional Integer $index
1385 function _stringShift(&$string, $index = 1)
1387 $substr = substr($string, 0, $index);
1388 $string = substr($string, $index);
1393 * Generate CTR XOR encryption key
1395 * Encrypt the output of this and XOR it against the ciphertext / plaintext to get the
1396 * plaintext / ciphertext in CTR mode.
1398 * @see Crypt_Base::decrypt()
1399 * @see Crypt_Base::encrypt()
1401 * @param Integer $length
1403 * @return String $xor
1405 function _generateXor(&$iv, $length)
1408 $block_size = $this->block_size;
1409 $num_blocks = floor(($length + ($block_size - 1)) / $block_size);
1410 for ($i = 0; $i < $num_blocks; $i++) {
1412 for ($j = 4; $j <= $block_size; $j+= 4) {
1413 $temp = substr($iv, -$j, 4);
1415 case "\xFF\xFF\xFF\xFF":
1416 $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4);
1418 case "\x7F\xFF\xFF\xFF":
1419 $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4);
1422 extract(unpack('Ncount', $temp));
1423 $iv = substr_replace($iv, pack('N', $count + 1), -$j, 4);
1433 * Setup the performance-optimized function for de/encrypt()
1435 * Stores the created (or existing) callback function-name
1436 * in $this->inline_crypt
1438 * Internally for phpseclib developers:
1440 * _setupInlineCrypt() would be called only if:
1442 * - $engine == CRYPT_MODE_INTERNAL and
1444 * - $use_inline_crypt === true
1446 * - each time on _setup(), after(!) _setupKey()
1449 * This ensures that _setupInlineCrypt() has allways a
1450 * full ready2go initializated internal cipher $engine state
1451 * where, for example, the keys allready expanded,
1452 * keys/block_size calculated and such.
1454 * It is, each time if called, the responsibility of _setupInlineCrypt():
1456 * - to set $this->inline_crypt to a valid and fully working callback function
1457 * as a (faster) replacement for encrypt() / decrypt()
1459 * - NOT to create unlimited callback functions (for memory reasons!)
1460 * no matter how often _setupInlineCrypt() would be called. At some
1461 * point of amount they must be generic re-useable.
1463 * - the code of _setupInlineCrypt() it self,
1464 * and the generated callback code,
1465 * must be, in following order:
1467 * - 100% compatible to encrypt()/decrypt()
1468 * - using only php5+ features/lang-constructs/php-extensions if
1469 * compatibility (down to php4) or fallback is provided
1470 * - readable/maintainable/understandable/commented and... not-cryptic-styled-code :-)
1471 * - >= 10% faster than encrypt()/decrypt() [which is, by the way,
1472 * the reason for the existence of _setupInlineCrypt() :-)]
1474 * - short (as good as possible)
1476 * Note: - _setupInlineCrypt() is using _createInlineCryptFunction() to create the full callback function code.
1477 * - In case of using inline crypting, _setupInlineCrypt() must extend by the child Crypt_* class.
1478 * - The following variable names are reserved:
1479 * - $_* (all variable names prefixed with an underscore)
1480 * - $self (object reference to it self. Do not use $this, but $self instead)
1481 * - $in (the content of $in has to en/decrypt by the generated code)
1482 * - The callback function should not use the 'return' statement, but en/decrypt'ing the content of $in only
1485 * @see Crypt_Base::_setup()
1486 * @see Crypt_Base::_createInlineCryptFunction()
1487 * @see Crypt_Base::encrypt()
1488 * @see Crypt_Base::decrypt()
1491 function _setupInlineCrypt()
1493 // If a Crypt_* class providing inline crypting it must extend _setupInlineCrypt()
1495 // If, for any reason, an extending Crypt_Base() Crypt_* class
1496 // not using inline crypting then it must be ensured that: $this->use_inline_crypt = false
1497 // ie in the class var declaration of $use_inline_crypt in general for the Crypt_* class,
1498 // in the constructor at object instance-time
1499 // or, if it's runtime-specific, at runtime
1501 $this->use_inline_crypt = false;
1505 * Creates the performance-optimized function for en/decrypt()
1507 * Internally for phpseclib developers:
1509 * _createInlineCryptFunction():
1511 * - merge the $cipher_code [setup'ed by _setupInlineCrypt()]
1512 * with the current [$this->]mode of operation code
1514 * - create the $inline function, which called by encrypt() / decrypt()
1515 * as its replacement to speed up the en/decryption operations.
1517 * - return the name of the created $inline callback function
1519 * - used to speed up en/decryption
1523 * The main reason why can speed up things [up to 50%] this way are:
1525 * - using variables more effective then regular.
1526 * (ie no use of expensive arrays but integers $k_0, $k_1 ...
1527 * or even, for example, the pure $key[] values hardcoded)
1529 * - avoiding 1000's of function calls of ie _encryptBlock()
1530 * but inlining the crypt operations.
1531 * in the mode of operation for() loop.
1533 * - full loop unroll the (sometimes key-dependent) rounds
1534 * avoiding this way ++$i counters and runtime-if's etc...
1536 * The basic code architectur of the generated $inline en/decrypt()
1537 * lambda function, in pseudo php, is:
1540 * +----------------------------------------------------------------------------------------------+
1541 * | callback $inline = create_function: |
1542 * | lambda_function_0001_crypt_ECB($action, $text) |
1544 * | INSERT PHP CODE OF: |
1545 * | $cipher_code['init_crypt']; // general init code. |
1546 * | // ie: $sbox'es declarations used for |
1547 * | // encrypt and decrypt'ing. |
1549 * | switch ($action) { |
1550 * | case 'encrypt': |
1551 * | INSERT PHP CODE OF: |
1552 * | $cipher_code['init_encrypt']; // encrypt sepcific init code. |
1553 * | ie: specified $key or $box |
1554 * | declarations for encrypt'ing. |
1556 * | foreach ($ciphertext) { |
1557 * | $in = $block_size of $ciphertext; |
1559 * | INSERT PHP CODE OF: |
1560 * | $cipher_code['encrypt_block']; // encrypt's (string) $in, which is always: |
1561 * | // strlen($in) == $this->block_size |
1562 * | // here comes the cipher algorithm in action |
1563 * | // for encryption. |
1564 * | // $cipher_code['encrypt_block'] has to |
1565 * | // encrypt the content of the $in variable |
1567 * | $plaintext .= $in; |
1569 * | return $plaintext; |
1571 * | case 'decrypt': |
1572 * | INSERT PHP CODE OF: |
1573 * | $cipher_code['init_decrypt']; // decrypt sepcific init code |
1574 * | ie: specified $key or $box |
1575 * | declarations for decrypt'ing. |
1576 * | foreach ($plaintext) { |
1577 * | $in = $block_size of $plaintext; |
1579 * | INSERT PHP CODE OF: |
1580 * | $cipher_code['decrypt_block']; // decrypt's (string) $in, which is always |
1581 * | // strlen($in) == $this->block_size |
1582 * | // here comes the cipher algorithm in action |
1583 * | // for decryption. |
1584 * | // $cipher_code['decrypt_block'] has to |
1585 * | // decrypt the content of the $in variable |
1586 * | $ciphertext .= $in; |
1588 * | return $ciphertext; |
1591 * +----------------------------------------------------------------------------------------------+
1594 * See also the Crypt_*::_setupInlineCrypt()'s for
1595 * productive inline $cipher_code's how they works.
1599 * $cipher_code = array(
1600 * 'init_crypt' => (string) '', // optional
1601 * 'init_encrypt' => (string) '', // optional
1602 * 'init_decrypt' => (string) '', // optional
1603 * 'encrypt_block' => (string) '', // required
1604 * 'decrypt_block' => (string) '' // required
1608 * @see Crypt_Base::_setupInlineCrypt()
1609 * @see Crypt_Base::encrypt()
1610 * @see Crypt_Base::decrypt()
1611 * @param Array $cipher_code
1613 * @return String (the name of the created callback function)
1615 function _createInlineCryptFunction($cipher_code)
1617 $block_size = $this->block_size;
1620 $init_crypt = isset($cipher_code['init_crypt']) ? $cipher_code['init_crypt'] : '';
1621 $init_encrypt = isset($cipher_code['init_encrypt']) ? $cipher_code['init_encrypt'] : '';
1622 $init_decrypt = isset($cipher_code['init_decrypt']) ? $cipher_code['init_decrypt'] : '';
1624 $encrypt_block = $cipher_code['encrypt_block'];
1625 $decrypt_block = $cipher_code['decrypt_block'];
1627 // Generating mode of operation inline code,
1628 // merged with the $cipher_code algorithm
1629 // for encrypt- and decryption.
1630 switch ($this->mode) {
1631 case CRYPT_MODE_ECB:
1632 $encrypt = $init_encrypt . '
1634 $_text = $self->_pad($_text);
1635 $_plaintext_len = strlen($_text);
1637 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1638 $in = substr($_text, $_i, '.$block_size.');
1643 return $_ciphertext;
1646 $decrypt = $init_decrypt . '
1648 $_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0));
1649 $_ciphertext_len = strlen($_text);
1651 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1652 $in = substr($_text, $_i, '.$block_size.');
1657 return $self->_unpad($_plaintext);
1660 case CRYPT_MODE_CTR:
1661 $encrypt = $init_encrypt . '
1663 $_plaintext_len = strlen($_text);
1664 $_xor = $self->encryptIV;
1665 $_buffer = &$self->enbuffer;
1667 if (strlen($_buffer["encrypted"])) {
1668 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1669 $_block = substr($_text, $_i, '.$block_size.');
1670 if (strlen($_block) > strlen($_buffer["encrypted"])) {
1671 $in = $self->_generateXor($_xor, '.$block_size.');
1673 $_buffer["encrypted"].= $in;
1675 $_key = $self->_stringShift($_buffer["encrypted"], '.$block_size.');
1676 $_ciphertext.= $_block ^ $_key;
1679 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1680 $_block = substr($_text, $_i, '.$block_size.');
1681 $in = $self->_generateXor($_xor, '.$block_size.');
1684 $_ciphertext.= $_block ^ $_key;
1687 if ($self->continuousBuffer) {
1688 $self->encryptIV = $_xor;
1689 if ($_start = $_plaintext_len % '.$block_size.') {
1690 $_buffer["encrypted"] = substr($_key, $_start) . $_buffer["encrypted"];
1694 return $_ciphertext;
1697 $decrypt = $init_encrypt . '
1699 $_ciphertext_len = strlen($_text);
1700 $_xor = $self->decryptIV;
1701 $_buffer = &$self->debuffer;
1703 if (strlen($_buffer["ciphertext"])) {
1704 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1705 $_block = substr($_text, $_i, '.$block_size.');
1706 if (strlen($_block) > strlen($_buffer["ciphertext"])) {
1707 $in = $self->_generateXor($_xor, '.$block_size.');
1709 $_buffer["ciphertext"].= $in;
1711 $_key = $self->_stringShift($_buffer["ciphertext"], '.$block_size.');
1712 $_plaintext.= $_block ^ $_key;
1715 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1716 $_block = substr($_text, $_i, '.$block_size.');
1717 $in = $self->_generateXor($_xor, '.$block_size.');
1720 $_plaintext.= $_block ^ $_key;
1723 if ($self->continuousBuffer) {
1724 $self->decryptIV = $_xor;
1725 if ($_start = $_ciphertext_len % '.$block_size.') {
1726 $_buffer["ciphertext"] = substr($_key, $_start) . $_buffer["ciphertext"];
1733 case CRYPT_MODE_CFB:
1734 $encrypt = $init_encrypt . '
1736 $_buffer = &$self->enbuffer;
1738 if ($self->continuousBuffer) {
1739 $_iv = &$self->encryptIV;
1740 $_pos = &$_buffer["pos"];
1742 $_iv = $self->encryptIV;
1745 $_len = strlen($_text);
1749 $_max = '.$block_size.' - $_pos;
1750 if ($_len >= $_max) {
1759 $_ciphertext = substr($_iv, $_orig_pos) ^ $_text;
1760 $_iv = substr_replace($_iv, $_ciphertext, $_orig_pos, $_i);
1762 while ($_len >= '.$block_size.') {
1765 $_iv = $in ^ substr($_text, $_i, '.$block_size.');
1766 $_ciphertext.= $_iv;
1767 $_len-= '.$block_size.';
1768 $_i+= '.$block_size.';
1774 $_block = $_iv ^ substr($_text, $_i);
1775 $_iv = substr_replace($_iv, $_block, 0, $_len);
1776 $_ciphertext.= $_block;
1779 return $_ciphertext;
1782 $decrypt = $init_encrypt . '
1784 $_buffer = &$self->debuffer;
1786 if ($self->continuousBuffer) {
1787 $_iv = &$self->decryptIV;
1788 $_pos = &$_buffer["pos"];
1790 $_iv = $self->decryptIV;
1793 $_len = strlen($_text);
1797 $_max = '.$block_size.' - $_pos;
1798 if ($_len >= $_max) {
1807 $_plaintext = substr($_iv, $_orig_pos) ^ $_text;
1808 $_iv = substr_replace($_iv, substr($_text, 0, $_i), $_orig_pos, $_i);
1810 while ($_len >= '.$block_size.') {
1814 $cb = substr($_text, $_i, '.$block_size.');
1815 $_plaintext.= $_iv ^ $cb;
1817 $_len-= '.$block_size.';
1818 $_i+= '.$block_size.';
1824 $_plaintext.= $_iv ^ substr($_text, $_i);
1825 $_iv = substr_replace($_iv, substr($_text, $_i), 0, $_len);
1832 case CRYPT_MODE_OFB:
1833 $encrypt = $init_encrypt . '
1835 $_plaintext_len = strlen($_text);
1836 $_xor = $self->encryptIV;
1837 $_buffer = &$self->enbuffer;
1839 if (strlen($_buffer["xor"])) {
1840 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1841 $_block = substr($_text, $_i, '.$block_size.');
1842 if (strlen($_block) > strlen($_buffer["xor"])) {
1846 $_buffer["xor"].= $_xor;
1848 $_key = $self->_stringShift($_buffer["xor"], '.$block_size.');
1849 $_ciphertext.= $_block ^ $_key;
1852 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1856 $_ciphertext.= substr($_text, $_i, '.$block_size.') ^ $_xor;
1860 if ($self->continuousBuffer) {
1861 $self->encryptIV = $_xor;
1862 if ($_start = $_plaintext_len % '.$block_size.') {
1863 $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
1866 return $_ciphertext;
1869 $decrypt = $init_encrypt . '
1871 $_ciphertext_len = strlen($_text);
1872 $_xor = $self->decryptIV;
1873 $_buffer = &$self->debuffer;
1875 if (strlen($_buffer["xor"])) {
1876 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1877 $_block = substr($_text, $_i, '.$block_size.');
1878 if (strlen($_block) > strlen($_buffer["xor"])) {
1882 $_buffer["xor"].= $_xor;
1884 $_key = $self->_stringShift($_buffer["xor"], '.$block_size.');
1885 $_plaintext.= $_block ^ $_key;
1888 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1892 $_plaintext.= substr($_text, $_i, '.$block_size.') ^ $_xor;
1896 if ($self->continuousBuffer) {
1897 $self->decryptIV = $_xor;
1898 if ($_start = $_ciphertext_len % '.$block_size.') {
1899 $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
1905 case CRYPT_MODE_STREAM:
1906 $encrypt = $init_encrypt . '
1909 return $_ciphertext;
1911 $decrypt = $init_decrypt . '
1917 // case CRYPT_MODE_CBC:
1919 $encrypt = $init_encrypt . '
1921 $_text = $self->_pad($_text);
1922 $_plaintext_len = strlen($_text);
1924 $in = $self->encryptIV;
1926 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1927 $in = substr($_text, $_i, '.$block_size.') ^ $in;
1932 if ($self->continuousBuffer) {
1933 $self->encryptIV = $in;
1936 return $_ciphertext;
1939 $decrypt = $init_decrypt . '
1941 $_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0));
1942 $_ciphertext_len = strlen($_text);
1944 $_iv = $self->decryptIV;
1946 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1947 $in = $_block = substr($_text, $_i, '.$block_size.');
1949 $_plaintext.= $in ^ $_iv;
1953 if ($self->continuousBuffer) {
1954 $self->decryptIV = $_iv;
1957 return $self->_unpad($_plaintext);
1962 // Create the $inline function and return its name as string. Ready to run!
1963 return create_function('$_action, &$self, $_text', $init_crypt . 'if ($_action == "encrypt") { ' . $encrypt . ' } else { ' . $decrypt . ' }');
1967 * Holds the lambda_functions table (classwide)
1969 * Each name of the lambda function, created from
1970 * _setupInlineCrypt() && _createInlineCryptFunction()
1971 * is stored, classwide (!), here for reusing.
1973 * The string-based index of $function is a classwide
1974 * uniqe value representing, at least, the $mode of
1975 * operation (or more... depends of the optimizing level)
1976 * for which $mode the lambda function was created.
1981 function &_getLambdaFunctions()
1983 static $functions = array();
1988 // vim: ts=4:sw=4:et: