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 2007 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} or pbkdf1:
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
557 function setPassword($password, $method = 'pbkdf2')
562 default: // 'pbkdf2' or 'pbkdf1'
563 $func_args = func_get_args();
566 $hash = isset($func_args[2]) ? $func_args[2] : 'sha1';
568 // WPA and WPA2 use the SSID as the salt
569 $salt = isset($func_args[3]) ? $func_args[3] : $this->password_default_salt;
571 // RFC2898#section-4.2 uses 1,000 iterations by default
572 // WPA and WPA2 use 4,096.
573 $count = isset($func_args[4]) ? $func_args[4] : 1000;
576 if (isset($func_args[5])) {
577 $dkLen = $func_args[5];
579 $dkLen = $method == 'pbkdf1' ? 2 * $this->password_key_size : $this->password_key_size;
583 case $method == 'pbkdf1':
584 if (!class_exists('Crypt_Hash')) {
585 include_once 'Crypt/Hash.php';
587 $hashObj = new Crypt_Hash();
588 $hashObj->setHash($hash);
589 if ($dkLen > $hashObj->getLength()) {
590 user_error('Derived key too long');
593 $t = $password . $salt;
594 for ($i = 0; $i < $count; ++$i) {
595 $t = $hashObj->hash($t);
597 $key = substr($t, 0, $dkLen);
599 $this->setKey(substr($key, 0, $dkLen >> 1));
600 $this->setIV(substr($key, $dkLen >> 1));
603 // Determining if php[>=5.5.0]'s hash_pbkdf2() function avail- and useable
604 case !function_exists('hash_pbkdf2'):
605 case !function_exists('hash_algos'):
606 case !in_array($hash, hash_algos()):
607 if (!class_exists('Crypt_Hash')) {
608 include_once 'Crypt/Hash.php';
611 while (strlen($key) < $dkLen) {
612 $hmac = new Crypt_Hash();
613 $hmac->setHash($hash);
614 $hmac->setKey($password);
615 $f = $u = $hmac->hash($salt . pack('N', $i++));
616 for ($j = 2; $j <= $count; ++$j) {
617 $u = $hmac->hash($u);
622 $key = substr($key, 0, $dkLen);
625 $key = hash_pbkdf2($hash, $password, $salt, $count, $dkLen, true);
635 * Encrypts a message.
637 * $plaintext will be padded with additional bytes such that it's length is a multiple of the block size. Other cipher
638 * implementations may or may not pad in the same manner. Other common approaches to padding and the reasons why it's
639 * necessary are discussed in the following
642 * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
644 * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does.
645 * strlen($plaintext) will still need to be a multiple of the block size, however, arbitrary values can be added to make it that
648 * Note: Could, but not must, extend by the child Crypt_* class
650 * @see Crypt_Base::decrypt()
652 * @param String $plaintext
653 * @return String $cipertext
655 function encrypt($plaintext)
657 if ($this->engine == CRYPT_MODE_MCRYPT) {
658 if ($this->changed) {
659 $this->_setupMcrypt();
660 $this->changed = false;
662 if ($this->enchanged) {
663 mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
664 $this->enchanged = false;
667 // re: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
668 // using mcrypt's default handing of CFB the above would output two different things. using phpseclib's
669 // rewritten CFB implementation the above outputs the same thing twice.
670 if ($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer) {
671 $block_size = $this->block_size;
672 $iv = &$this->encryptIV;
673 $pos = &$this->enbuffer['pos'];
674 $len = strlen($plaintext);
679 $max = $block_size - $pos;
689 $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
690 $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
691 $this->enbuffer['enmcrypt_init'] = true;
693 if ($len >= $block_size) {
694 if ($this->enbuffer['enmcrypt_init'] === false || $len > $this->cfb_init_len) {
695 if ($this->enbuffer['enmcrypt_init'] === true) {
696 mcrypt_generic_init($this->enmcrypt, $this->key, $iv);
697 $this->enbuffer['enmcrypt_init'] = false;
699 $ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % $block_size));
700 $iv = substr($ciphertext, -$block_size);
703 while ($len >= $block_size) {
704 $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, $block_size);
713 $iv = mcrypt_generic($this->ecb, $iv);
714 $block = $iv ^ substr($plaintext, -$len);
715 $iv = substr_replace($iv, $block, 0, $len);
716 $ciphertext.= $block;
723 if ($this->paddable) {
724 $plaintext = $this->_pad($plaintext);
727 $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
729 if (!$this->continuousBuffer) {
730 mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
736 if ($this->changed) {
738 $this->changed = false;
740 if ($this->use_inline_crypt) {
741 $inline = $this->inline_crypt;
742 return $inline('encrypt', $this, $plaintext);
744 if ($this->paddable) {
745 $plaintext = $this->_pad($plaintext);
748 $buffer = &$this->enbuffer;
749 $block_size = $this->block_size;
751 switch ($this->mode) {
753 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
754 $ciphertext.= $this->_encryptBlock(substr($plaintext, $i, $block_size));
758 $xor = $this->encryptIV;
759 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
760 $block = substr($plaintext, $i, $block_size);
761 $block = $this->_encryptBlock($block ^ $xor);
763 $ciphertext.= $block;
765 if ($this->continuousBuffer) {
766 $this->encryptIV = $xor;
770 $xor = $this->encryptIV;
771 if (strlen($buffer['encrypted'])) {
772 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
773 $block = substr($plaintext, $i, $block_size);
774 if (strlen($block) > strlen($buffer['encrypted'])) {
775 $buffer['encrypted'].= $this->_encryptBlock($this->_generateXor($xor, $block_size));
777 $key = $this->_stringShift($buffer['encrypted'], $block_size);
778 $ciphertext.= $block ^ $key;
781 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
782 $block = substr($plaintext, $i, $block_size);
783 $key = $this->_encryptBlock($this->_generateXor($xor, $block_size));
784 $ciphertext.= $block ^ $key;
787 if ($this->continuousBuffer) {
788 $this->encryptIV = $xor;
789 if ($start = strlen($plaintext) % $block_size) {
790 $buffer['encrypted'] = substr($key, $start) . $buffer['encrypted'];
795 // cfb loosely routines inspired by openssl's:
796 // {@link http://cvs.openssl.org/fileview?f=openssl/crypto/modes/cfb128.c&v=1.3.2.2.2.1}
797 if ($this->continuousBuffer) {
798 $iv = &$this->encryptIV;
799 $pos = &$buffer['pos'];
801 $iv = $this->encryptIV;
804 $len = strlen($plaintext);
808 $max = $block_size - $pos;
818 // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
819 $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
820 $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
822 while ($len >= $block_size) {
823 $iv = $this->_encryptBlock($iv) ^ substr($plaintext, $i, $block_size);
829 $iv = $this->_encryptBlock($iv);
830 $block = $iv ^ substr($plaintext, $i);
831 $iv = substr_replace($iv, $block, 0, $len);
832 $ciphertext.= $block;
837 $xor = $this->encryptIV;
838 if (strlen($buffer['xor'])) {
839 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
840 $block = substr($plaintext, $i, $block_size);
841 if (strlen($block) > strlen($buffer['xor'])) {
842 $xor = $this->_encryptBlock($xor);
843 $buffer['xor'].= $xor;
845 $key = $this->_stringShift($buffer['xor'], $block_size);
846 $ciphertext.= $block ^ $key;
849 for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
850 $xor = $this->_encryptBlock($xor);
851 $ciphertext.= substr($plaintext, $i, $block_size) ^ $xor;
855 if ($this->continuousBuffer) {
856 $this->encryptIV = $xor;
857 if ($start = strlen($plaintext) % $block_size) {
858 $buffer['xor'] = substr($key, $start) . $buffer['xor'];
862 case CRYPT_MODE_STREAM:
863 $ciphertext = $this->_encryptBlock($plaintext);
871 * Decrypts a message.
873 * If strlen($ciphertext) is not a multiple of the block size, null bytes will be added to the end of the string until
876 * Note: Could, but not must, extend by the child Crypt_* class
878 * @see Crypt_Base::encrypt()
880 * @param String $ciphertext
881 * @return String $plaintext
883 function decrypt($ciphertext)
885 if ($this->engine == CRYPT_MODE_MCRYPT) {
886 $block_size = $this->block_size;
887 if ($this->changed) {
888 $this->_setupMcrypt();
889 $this->changed = false;
891 if ($this->dechanged) {
892 mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
893 $this->dechanged = false;
896 if ($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer) {
897 $iv = &$this->decryptIV;
898 $pos = &$this->debuffer['pos'];
899 $len = strlen($ciphertext);
904 $max = $block_size - $pos;
914 // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
915 $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
916 $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
918 if ($len >= $block_size) {
919 $cb = substr($ciphertext, $i, $len - $len % $block_size);
920 $plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
921 $iv = substr($cb, -$block_size);
925 $iv = mcrypt_generic($this->ecb, $iv);
926 $plaintext.= $iv ^ substr($ciphertext, -$len);
927 $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len);
934 if ($this->paddable) {
935 // we pad with chr(0) since that's what mcrypt_generic does. to quote from {@link http://www.php.net/function.mcrypt-generic}:
936 // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
937 $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($block_size - strlen($ciphertext) % $block_size) % $block_size, chr(0));
940 $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
942 if (!$this->continuousBuffer) {
943 mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
946 return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
949 if ($this->changed) {
951 $this->changed = false;
953 if ($this->use_inline_crypt) {
954 $inline = $this->inline_crypt;
955 return $inline('decrypt', $this, $ciphertext);
958 $block_size = $this->block_size;
959 if ($this->paddable) {
960 // we pad with chr(0) since that's what mcrypt_generic does [...]
961 $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($block_size - strlen($ciphertext) % $block_size) % $block_size, chr(0));
964 $buffer = &$this->debuffer;
966 switch ($this->mode) {
968 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
969 $plaintext.= $this->_decryptBlock(substr($ciphertext, $i, $block_size));
973 $xor = $this->decryptIV;
974 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
975 $block = substr($ciphertext, $i, $block_size);
976 $plaintext.= $this->_decryptBlock($block) ^ $xor;
979 if ($this->continuousBuffer) {
980 $this->decryptIV = $xor;
984 $xor = $this->decryptIV;
985 if (strlen($buffer['ciphertext'])) {
986 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
987 $block = substr($ciphertext, $i, $block_size);
988 if (strlen($block) > strlen($buffer['ciphertext'])) {
989 $buffer['ciphertext'].= $this->_encryptBlock($this->_generateXor($xor, $block_size));
991 $key = $this->_stringShift($buffer['ciphertext'], $block_size);
992 $plaintext.= $block ^ $key;
995 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
996 $block = substr($ciphertext, $i, $block_size);
997 $key = $this->_encryptBlock($this->_generateXor($xor, $block_size));
998 $plaintext.= $block ^ $key;
1001 if ($this->continuousBuffer) {
1002 $this->decryptIV = $xor;
1003 if ($start = strlen($ciphertext) % $block_size) {
1004 $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext'];
1008 case CRYPT_MODE_CFB:
1009 if ($this->continuousBuffer) {
1010 $iv = &$this->decryptIV;
1011 $pos = &$buffer['pos'];
1013 $iv = $this->decryptIV;
1016 $len = strlen($ciphertext);
1020 $max = $block_size - $pos;
1030 // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
1031 $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
1032 $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
1034 while ($len >= $block_size) {
1035 $iv = $this->_encryptBlock($iv);
1036 $cb = substr($ciphertext, $i, $block_size);
1037 $plaintext.= $iv ^ $cb;
1043 $iv = $this->_encryptBlock($iv);
1044 $plaintext.= $iv ^ substr($ciphertext, $i);
1045 $iv = substr_replace($iv, substr($ciphertext, $i), 0, $len);
1049 case CRYPT_MODE_OFB:
1050 $xor = $this->decryptIV;
1051 if (strlen($buffer['xor'])) {
1052 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
1053 $block = substr($ciphertext, $i, $block_size);
1054 if (strlen($block) > strlen($buffer['xor'])) {
1055 $xor = $this->_encryptBlock($xor);
1056 $buffer['xor'].= $xor;
1058 $key = $this->_stringShift($buffer['xor'], $block_size);
1059 $plaintext.= $block ^ $key;
1062 for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
1063 $xor = $this->_encryptBlock($xor);
1064 $plaintext.= substr($ciphertext, $i, $block_size) ^ $xor;
1068 if ($this->continuousBuffer) {
1069 $this->decryptIV = $xor;
1070 if ($start = strlen($ciphertext) % $block_size) {
1071 $buffer['xor'] = substr($key, $start) . $buffer['xor'];
1075 case CRYPT_MODE_STREAM:
1076 $plaintext = $this->_decryptBlock($ciphertext);
1079 return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
1085 * Block ciphers working by encrypting between their specified [$this->]block_size at a time
1086 * If you ever need to encrypt or decrypt something that isn't of the proper length, it becomes necessary to
1087 * pad the input so that it is of the proper length.
1089 * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH,
1090 * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping
1091 * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is
1092 * transmitted separately)
1094 * @see Crypt_Base::disablePadding()
1097 function enablePadding()
1099 $this->padding = true;
1103 * Do not pad packets.
1105 * @see Crypt_Base::enablePadding()
1108 function disablePadding()
1110 $this->padding = false;
1114 * Treat consecutive "packets" as if they are a continuous buffer.
1116 * Say you have a 32-byte plaintext $plaintext. Using the default behavior, the two following code snippets
1117 * will yield different outputs:
1120 * echo $rijndael->encrypt(substr($plaintext, 0, 16));
1121 * echo $rijndael->encrypt(substr($plaintext, 16, 16));
1124 * echo $rijndael->encrypt($plaintext);
1127 * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
1128 * another, as demonstrated with the following:
1131 * $rijndael->encrypt(substr($plaintext, 0, 16));
1132 * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
1135 * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
1138 * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
1139 * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
1140 * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
1142 * Put another way, when the continuous buffer is enabled, the state of the Crypt_*() object changes after each
1143 * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
1144 * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
1145 * however, they are also less intuitive and more likely to cause you problems.
1147 * Note: Could, but not must, extend by the child Crypt_* class
1149 * @see Crypt_Base::disableContinuousBuffer()
1152 function enableContinuousBuffer()
1154 if ($this->mode == CRYPT_MODE_ECB) {
1158 $this->continuousBuffer = true;
1162 * Treat consecutive packets as if they are a discontinuous buffer.
1164 * The default behavior.
1166 * Note: Could, but not must, extend by the child Crypt_* class
1168 * @see Crypt_Base::enableContinuousBuffer()
1171 function disableContinuousBuffer()
1173 if ($this->mode == CRYPT_MODE_ECB) {
1176 if (!$this->continuousBuffer) {
1180 $this->continuousBuffer = false;
1181 $this->changed = true;
1187 * Note: Must extend by the child Crypt_* class
1193 function _encryptBlock($in)
1195 user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
1201 * Note: Must extend by the child Crypt_* class
1207 function _decryptBlock($in)
1209 user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
1213 * Setup the key (expansion)
1215 * Only used if $engine == CRYPT_MODE_INTERNAL
1217 * Note: Must extend by the child Crypt_* class
1219 * @see Crypt_Base::_setup()
1222 function _setupKey()
1224 user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
1228 * Setup the CRYPT_MODE_INTERNAL $engine
1230 * (re)init, if necessary, the internal cipher $engine and flush all $buffers
1231 * Used (only) if $engine == CRYPT_MODE_INTERNAL
1233 * _setup() will be called each time if $changed === true
1234 * typically this happens when using one or more of following public methods:
1240 * - disableContinuousBuffer()
1242 * - First run of encrypt() / decrypt() with no init-settings
1244 * Internally: _setup() is called always before(!) en/decryption.
1246 * Note: Could, but not must, extend by the child Crypt_* class
1250 * @see disableContinuousBuffer()
1255 $this->_clearBuffers();
1258 if ($this->use_inline_crypt) {
1259 $this->_setupInlineCrypt();
1264 * Setup the CRYPT_MODE_MCRYPT $engine
1266 * (re)init, if necessary, the (ext)mcrypt resources and flush all $buffers
1267 * Used (only) if $engine = CRYPT_MODE_MCRYPT
1269 * _setupMcrypt() will be called each time if $changed === true
1270 * typically this happens when using one or more of following public methods:
1276 * - disableContinuousBuffer()
1278 * - First run of encrypt() / decrypt()
1281 * Note: Could, but not must, extend by the child Crypt_* class
1285 * @see disableContinuousBuffer()
1288 function _setupMcrypt()
1290 $this->_clearBuffers();
1291 $this->enchanged = $this->dechanged = true;
1293 if (!isset($this->enmcrypt)) {
1294 static $mcrypt_modes = array(
1295 CRYPT_MODE_CTR => 'ctr',
1296 CRYPT_MODE_ECB => MCRYPT_MODE_ECB,
1297 CRYPT_MODE_CBC => MCRYPT_MODE_CBC,
1298 CRYPT_MODE_CFB => 'ncfb',
1299 CRYPT_MODE_OFB => MCRYPT_MODE_NOFB,
1300 CRYPT_MODE_STREAM => MCRYPT_MODE_STREAM,
1303 $this->demcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
1304 $this->enmcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
1306 // we need the $ecb mcrypt resource (only) in MODE_CFB with enableContinuousBuffer()
1307 // to workaround mcrypt's broken ncfb implementation in buffered mode
1308 // see: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
1309 if ($this->mode == CRYPT_MODE_CFB) {
1310 $this->ecb = mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, '');
1313 } // else should mcrypt_generic_deinit be called?
1315 if ($this->mode == CRYPT_MODE_CFB) {
1316 mcrypt_generic_init($this->ecb, $this->key, str_repeat("\0", $this->block_size));
1323 * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize.
1324 * $this->block_size - (strlen($text) % $this->block_size) bytes are added, each of which is equal to
1325 * chr($this->block_size - (strlen($text) % $this->block_size)
1327 * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless
1328 * and padding will, hence forth, be enabled.
1330 * @see Crypt_Base::_unpad()
1331 * @param String $text
1335 function _pad($text)
1337 $length = strlen($text);
1339 if (!$this->padding) {
1340 if ($length % $this->block_size == 0) {
1343 user_error("The plaintext's length ($length) is not a multiple of the block size ({$this->block_size})");
1344 $this->padding = true;
1348 $pad = $this->block_size - ($length % $this->block_size);
1350 return str_pad($text, $length + $pad, chr($pad));
1356 * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong
1357 * and false will be returned.
1359 * @see Crypt_Base::_pad()
1360 * @param String $text
1364 function _unpad($text)
1366 if (!$this->padding) {
1370 $length = ord($text[strlen($text) - 1]);
1372 if (!$length || $length > $this->block_size) {
1376 return substr($text, 0, -$length);
1380 * Clears internal buffers
1382 * Clearing/resetting the internal buffers is done everytime
1383 * after disableContinuousBuffer() or on cipher $engine (re)init
1384 * ie after setKey() or setIV()
1386 * Note: Could, but not must, extend by the child Crypt_* class
1390 function _clearBuffers()
1392 $this->enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
1393 $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true);
1395 // mcrypt's handling of invalid's $iv:
1396 // $this->encryptIV = $this->decryptIV = strlen($this->iv) == $this->block_size ? $this->iv : str_repeat("\0", $this->block_size);
1397 $this->encryptIV = $this->decryptIV = str_pad(substr($this->iv, 0, $this->block_size), $this->block_size, "\0");
1403 * Inspired by array_shift
1405 * @param String $string
1406 * @param optional Integer $index
1410 function _stringShift(&$string, $index = 1)
1412 $substr = substr($string, 0, $index);
1413 $string = substr($string, $index);
1418 * Generate CTR XOR encryption key
1420 * Encrypt the output of this and XOR it against the ciphertext / plaintext to get the
1421 * plaintext / ciphertext in CTR mode.
1423 * @see Crypt_Base::decrypt()
1424 * @see Crypt_Base::encrypt()
1426 * @param Integer $length
1428 * @return String $xor
1430 function _generateXor(&$iv, $length)
1433 $block_size = $this->block_size;
1434 $num_blocks = floor(($length + ($block_size - 1)) / $block_size);
1435 for ($i = 0; $i < $num_blocks; $i++) {
1437 for ($j = 4; $j <= $block_size; $j+= 4) {
1438 $temp = substr($iv, -$j, 4);
1440 case "\xFF\xFF\xFF\xFF":
1441 $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4);
1443 case "\x7F\xFF\xFF\xFF":
1444 $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4);
1447 extract(unpack('Ncount', $temp));
1448 $iv = substr_replace($iv, pack('N', $count + 1), -$j, 4);
1458 * Setup the performance-optimized function for de/encrypt()
1460 * Stores the created (or existing) callback function-name
1461 * in $this->inline_crypt
1463 * Internally for phpseclib developers:
1465 * _setupInlineCrypt() would be called only if:
1467 * - $engine == CRYPT_MODE_INTERNAL and
1469 * - $use_inline_crypt === true
1471 * - each time on _setup(), after(!) _setupKey()
1474 * This ensures that _setupInlineCrypt() has always a
1475 * full ready2go initializated internal cipher $engine state
1476 * where, for example, the keys allready expanded,
1477 * keys/block_size calculated and such.
1479 * It is, each time if called, the responsibility of _setupInlineCrypt():
1481 * - to set $this->inline_crypt to a valid and fully working callback function
1482 * as a (faster) replacement for encrypt() / decrypt()
1484 * - NOT to create unlimited callback functions (for memory reasons!)
1485 * no matter how often _setupInlineCrypt() would be called. At some
1486 * point of amount they must be generic re-useable.
1488 * - the code of _setupInlineCrypt() it self,
1489 * and the generated callback code,
1490 * must be, in following order:
1492 * - 100% compatible to encrypt()/decrypt()
1493 * - using only php5+ features/lang-constructs/php-extensions if
1494 * compatibility (down to php4) or fallback is provided
1495 * - readable/maintainable/understandable/commented and... not-cryptic-styled-code :-)
1496 * - >= 10% faster than encrypt()/decrypt() [which is, by the way,
1497 * the reason for the existence of _setupInlineCrypt() :-)]
1499 * - short (as good as possible)
1501 * Note: - _setupInlineCrypt() is using _createInlineCryptFunction() to create the full callback function code.
1502 * - In case of using inline crypting, _setupInlineCrypt() must extend by the child Crypt_* class.
1503 * - The following variable names are reserved:
1504 * - $_* (all variable names prefixed with an underscore)
1505 * - $self (object reference to it self. Do not use $this, but $self instead)
1506 * - $in (the content of $in has to en/decrypt by the generated code)
1507 * - The callback function should not use the 'return' statement, but en/decrypt'ing the content of $in only
1510 * @see Crypt_Base::_setup()
1511 * @see Crypt_Base::_createInlineCryptFunction()
1512 * @see Crypt_Base::encrypt()
1513 * @see Crypt_Base::decrypt()
1516 function _setupInlineCrypt()
1518 // If a Crypt_* class providing inline crypting it must extend _setupInlineCrypt()
1520 // If, for any reason, an extending Crypt_Base() Crypt_* class
1521 // not using inline crypting then it must be ensured that: $this->use_inline_crypt = false
1522 // ie in the class var declaration of $use_inline_crypt in general for the Crypt_* class,
1523 // in the constructor at object instance-time
1524 // or, if it's runtime-specific, at runtime
1526 $this->use_inline_crypt = false;
1530 * Creates the performance-optimized function for en/decrypt()
1532 * Internally for phpseclib developers:
1534 * _createInlineCryptFunction():
1536 * - merge the $cipher_code [setup'ed by _setupInlineCrypt()]
1537 * with the current [$this->]mode of operation code
1539 * - create the $inline function, which called by encrypt() / decrypt()
1540 * as its replacement to speed up the en/decryption operations.
1542 * - return the name of the created $inline callback function
1544 * - used to speed up en/decryption
1548 * The main reason why can speed up things [up to 50%] this way are:
1550 * - using variables more effective then regular.
1551 * (ie no use of expensive arrays but integers $k_0, $k_1 ...
1552 * or even, for example, the pure $key[] values hardcoded)
1554 * - avoiding 1000's of function calls of ie _encryptBlock()
1555 * but inlining the crypt operations.
1556 * in the mode of operation for() loop.
1558 * - full loop unroll the (sometimes key-dependent) rounds
1559 * avoiding this way ++$i counters and runtime-if's etc...
1561 * The basic code architectur of the generated $inline en/decrypt()
1562 * lambda function, in pseudo php, is:
1565 * +----------------------------------------------------------------------------------------------+
1566 * | callback $inline = create_function: |
1567 * | lambda_function_0001_crypt_ECB($action, $text) |
1569 * | INSERT PHP CODE OF: |
1570 * | $cipher_code['init_crypt']; // general init code. |
1571 * | // ie: $sbox'es declarations used for |
1572 * | // encrypt and decrypt'ing. |
1574 * | switch ($action) { |
1575 * | case 'encrypt': |
1576 * | INSERT PHP CODE OF: |
1577 * | $cipher_code['init_encrypt']; // encrypt sepcific init code. |
1578 * | ie: specified $key or $box |
1579 * | declarations for encrypt'ing. |
1581 * | foreach ($ciphertext) { |
1582 * | $in = $block_size of $ciphertext; |
1584 * | INSERT PHP CODE OF: |
1585 * | $cipher_code['encrypt_block']; // encrypt's (string) $in, which is always: |
1586 * | // strlen($in) == $this->block_size |
1587 * | // here comes the cipher algorithm in action |
1588 * | // for encryption. |
1589 * | // $cipher_code['encrypt_block'] has to |
1590 * | // encrypt the content of the $in variable |
1592 * | $plaintext .= $in; |
1594 * | return $plaintext; |
1596 * | case 'decrypt': |
1597 * | INSERT PHP CODE OF: |
1598 * | $cipher_code['init_decrypt']; // decrypt sepcific init code |
1599 * | ie: specified $key or $box |
1600 * | declarations for decrypt'ing. |
1601 * | foreach ($plaintext) { |
1602 * | $in = $block_size of $plaintext; |
1604 * | INSERT PHP CODE OF: |
1605 * | $cipher_code['decrypt_block']; // decrypt's (string) $in, which is always |
1606 * | // strlen($in) == $this->block_size |
1607 * | // here comes the cipher algorithm in action |
1608 * | // for decryption. |
1609 * | // $cipher_code['decrypt_block'] has to |
1610 * | // decrypt the content of the $in variable |
1611 * | $ciphertext .= $in; |
1613 * | return $ciphertext; |
1616 * +----------------------------------------------------------------------------------------------+
1619 * See also the Crypt_*::_setupInlineCrypt()'s for
1620 * productive inline $cipher_code's how they works.
1624 * $cipher_code = array(
1625 * 'init_crypt' => (string) '', // optional
1626 * 'init_encrypt' => (string) '', // optional
1627 * 'init_decrypt' => (string) '', // optional
1628 * 'encrypt_block' => (string) '', // required
1629 * 'decrypt_block' => (string) '' // required
1633 * @see Crypt_Base::_setupInlineCrypt()
1634 * @see Crypt_Base::encrypt()
1635 * @see Crypt_Base::decrypt()
1636 * @param Array $cipher_code
1638 * @return String (the name of the created callback function)
1640 function _createInlineCryptFunction($cipher_code)
1642 $block_size = $this->block_size;
1645 $init_crypt = isset($cipher_code['init_crypt']) ? $cipher_code['init_crypt'] : '';
1646 $init_encrypt = isset($cipher_code['init_encrypt']) ? $cipher_code['init_encrypt'] : '';
1647 $init_decrypt = isset($cipher_code['init_decrypt']) ? $cipher_code['init_decrypt'] : '';
1649 $encrypt_block = $cipher_code['encrypt_block'];
1650 $decrypt_block = $cipher_code['decrypt_block'];
1652 // Generating mode of operation inline code,
1653 // merged with the $cipher_code algorithm
1654 // for encrypt- and decryption.
1655 switch ($this->mode) {
1656 case CRYPT_MODE_ECB:
1657 $encrypt = $init_encrypt . '
1659 $_text = $self->_pad($_text);
1660 $_plaintext_len = strlen($_text);
1662 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1663 $in = substr($_text, $_i, '.$block_size.');
1668 return $_ciphertext;
1671 $decrypt = $init_decrypt . '
1673 $_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0));
1674 $_ciphertext_len = strlen($_text);
1676 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1677 $in = substr($_text, $_i, '.$block_size.');
1682 return $self->_unpad($_plaintext);
1685 case CRYPT_MODE_CTR:
1686 $encrypt = $init_encrypt . '
1688 $_plaintext_len = strlen($_text);
1689 $_xor = $self->encryptIV;
1690 $_buffer = &$self->enbuffer;
1692 if (strlen($_buffer["encrypted"])) {
1693 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1694 $_block = substr($_text, $_i, '.$block_size.');
1695 if (strlen($_block) > strlen($_buffer["encrypted"])) {
1696 $in = $self->_generateXor($_xor, '.$block_size.');
1698 $_buffer["encrypted"].= $in;
1700 $_key = $self->_stringShift($_buffer["encrypted"], '.$block_size.');
1701 $_ciphertext.= $_block ^ $_key;
1704 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1705 $_block = substr($_text, $_i, '.$block_size.');
1706 $in = $self->_generateXor($_xor, '.$block_size.');
1709 $_ciphertext.= $_block ^ $_key;
1712 if ($self->continuousBuffer) {
1713 $self->encryptIV = $_xor;
1714 if ($_start = $_plaintext_len % '.$block_size.') {
1715 $_buffer["encrypted"] = substr($_key, $_start) . $_buffer["encrypted"];
1719 return $_ciphertext;
1722 $decrypt = $init_encrypt . '
1724 $_ciphertext_len = strlen($_text);
1725 $_xor = $self->decryptIV;
1726 $_buffer = &$self->debuffer;
1728 if (strlen($_buffer["ciphertext"])) {
1729 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1730 $_block = substr($_text, $_i, '.$block_size.');
1731 if (strlen($_block) > strlen($_buffer["ciphertext"])) {
1732 $in = $self->_generateXor($_xor, '.$block_size.');
1734 $_buffer["ciphertext"].= $in;
1736 $_key = $self->_stringShift($_buffer["ciphertext"], '.$block_size.');
1737 $_plaintext.= $_block ^ $_key;
1740 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1741 $_block = substr($_text, $_i, '.$block_size.');
1742 $in = $self->_generateXor($_xor, '.$block_size.');
1745 $_plaintext.= $_block ^ $_key;
1748 if ($self->continuousBuffer) {
1749 $self->decryptIV = $_xor;
1750 if ($_start = $_ciphertext_len % '.$block_size.') {
1751 $_buffer["ciphertext"] = substr($_key, $_start) . $_buffer["ciphertext"];
1758 case CRYPT_MODE_CFB:
1759 $encrypt = $init_encrypt . '
1761 $_buffer = &$self->enbuffer;
1763 if ($self->continuousBuffer) {
1764 $_iv = &$self->encryptIV;
1765 $_pos = &$_buffer["pos"];
1767 $_iv = $self->encryptIV;
1770 $_len = strlen($_text);
1774 $_max = '.$block_size.' - $_pos;
1775 if ($_len >= $_max) {
1784 $_ciphertext = substr($_iv, $_orig_pos) ^ $_text;
1785 $_iv = substr_replace($_iv, $_ciphertext, $_orig_pos, $_i);
1787 while ($_len >= '.$block_size.') {
1790 $_iv = $in ^ substr($_text, $_i, '.$block_size.');
1791 $_ciphertext.= $_iv;
1792 $_len-= '.$block_size.';
1793 $_i+= '.$block_size.';
1799 $_block = $_iv ^ substr($_text, $_i);
1800 $_iv = substr_replace($_iv, $_block, 0, $_len);
1801 $_ciphertext.= $_block;
1804 return $_ciphertext;
1807 $decrypt = $init_encrypt . '
1809 $_buffer = &$self->debuffer;
1811 if ($self->continuousBuffer) {
1812 $_iv = &$self->decryptIV;
1813 $_pos = &$_buffer["pos"];
1815 $_iv = $self->decryptIV;
1818 $_len = strlen($_text);
1822 $_max = '.$block_size.' - $_pos;
1823 if ($_len >= $_max) {
1832 $_plaintext = substr($_iv, $_orig_pos) ^ $_text;
1833 $_iv = substr_replace($_iv, substr($_text, 0, $_i), $_orig_pos, $_i);
1835 while ($_len >= '.$block_size.') {
1839 $cb = substr($_text, $_i, '.$block_size.');
1840 $_plaintext.= $_iv ^ $cb;
1842 $_len-= '.$block_size.';
1843 $_i+= '.$block_size.';
1849 $_plaintext.= $_iv ^ substr($_text, $_i);
1850 $_iv = substr_replace($_iv, substr($_text, $_i), 0, $_len);
1857 case CRYPT_MODE_OFB:
1858 $encrypt = $init_encrypt . '
1860 $_plaintext_len = strlen($_text);
1861 $_xor = $self->encryptIV;
1862 $_buffer = &$self->enbuffer;
1864 if (strlen($_buffer["xor"])) {
1865 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1866 $_block = substr($_text, $_i, '.$block_size.');
1867 if (strlen($_block) > strlen($_buffer["xor"])) {
1871 $_buffer["xor"].= $_xor;
1873 $_key = $self->_stringShift($_buffer["xor"], '.$block_size.');
1874 $_ciphertext.= $_block ^ $_key;
1877 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1881 $_ciphertext.= substr($_text, $_i, '.$block_size.') ^ $_xor;
1885 if ($self->continuousBuffer) {
1886 $self->encryptIV = $_xor;
1887 if ($_start = $_plaintext_len % '.$block_size.') {
1888 $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
1891 return $_ciphertext;
1894 $decrypt = $init_encrypt . '
1896 $_ciphertext_len = strlen($_text);
1897 $_xor = $self->decryptIV;
1898 $_buffer = &$self->debuffer;
1900 if (strlen($_buffer["xor"])) {
1901 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1902 $_block = substr($_text, $_i, '.$block_size.');
1903 if (strlen($_block) > strlen($_buffer["xor"])) {
1907 $_buffer["xor"].= $_xor;
1909 $_key = $self->_stringShift($_buffer["xor"], '.$block_size.');
1910 $_plaintext.= $_block ^ $_key;
1913 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1917 $_plaintext.= substr($_text, $_i, '.$block_size.') ^ $_xor;
1921 if ($self->continuousBuffer) {
1922 $self->decryptIV = $_xor;
1923 if ($_start = $_ciphertext_len % '.$block_size.') {
1924 $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
1930 case CRYPT_MODE_STREAM:
1931 $encrypt = $init_encrypt . '
1934 return $_ciphertext;
1936 $decrypt = $init_decrypt . '
1942 // case CRYPT_MODE_CBC:
1944 $encrypt = $init_encrypt . '
1946 $_text = $self->_pad($_text);
1947 $_plaintext_len = strlen($_text);
1949 $in = $self->encryptIV;
1951 for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
1952 $in = substr($_text, $_i, '.$block_size.') ^ $in;
1957 if ($self->continuousBuffer) {
1958 $self->encryptIV = $in;
1961 return $_ciphertext;
1964 $decrypt = $init_decrypt . '
1966 $_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0));
1967 $_ciphertext_len = strlen($_text);
1969 $_iv = $self->decryptIV;
1971 for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
1972 $in = $_block = substr($_text, $_i, '.$block_size.');
1974 $_plaintext.= $in ^ $_iv;
1978 if ($self->continuousBuffer) {
1979 $self->decryptIV = $_iv;
1982 return $self->_unpad($_plaintext);
1987 // Create the $inline function and return its name as string. Ready to run!
1988 return create_function('$_action, &$self, $_text', $init_crypt . 'if ($_action == "encrypt") { ' . $encrypt . ' } else { ' . $decrypt . ' }');
1992 * Holds the lambda_functions table (classwide)
1994 * Each name of the lambda function, created from
1995 * _setupInlineCrypt() && _createInlineCryptFunction()
1996 * is stored, classwide (!), here for reusing.
1998 * The string-based index of $function is a classwide
1999 * uniqe value representing, at least, the $mode of
2000 * operation (or more... depends of the optimizing level)
2001 * for which $mode the lambda function was created.
2006 function &_getLambdaFunctions()
2008 static $functions = array();