From 367ddebf805eb0071eb4b9deb3abf7e16866c040 Mon Sep 17 00:00:00 2001 From: Jim Wigginton Date: Mon, 2 Jul 2007 04:19:55 +0000 Subject: [PATCH] - initial commit git-svn-id: http://phpseclib.svn.sourceforge.net/svnroot/phpseclib/trunk@3 21d32557-59b3-4da0-833f-c5933fad653e --- phpseclib/Crypt/DES.php | 839 +++++++ phpseclib/Crypt/RC4.php | 421 ++++ phpseclib/Crypt/Random.php | 69 + phpseclib/Crypt/TripleDES.php | 564 +++++ phpseclib/Math/BigInteger.php | 2174 ++++++++++++++++++ phpseclib/Net/SSH1.php | 1126 +++++++++ phpseclib/PHP/Compat/Function/array_fill.php | 43 + phpseclib/PHP/Compat/Function/bcpowmod.php | 67 + 8 files changed, 5303 insertions(+) create mode 100644 phpseclib/Crypt/DES.php create mode 100644 phpseclib/Crypt/RC4.php create mode 100644 phpseclib/Crypt/Random.php create mode 100644 phpseclib/Crypt/TripleDES.php create mode 100644 phpseclib/Math/BigInteger.php create mode 100644 phpseclib/Net/SSH1.php create mode 100644 phpseclib/PHP/Compat/Function/array_fill.php create mode 100644 phpseclib/PHP/Compat/Function/bcpowmod.php diff --git a/phpseclib/Crypt/DES.php b/phpseclib/Crypt/DES.php new file mode 100644 index 00000000..b8324004 --- /dev/null +++ b/phpseclib/Crypt/DES.php @@ -0,0 +1,839 @@ + + * setKey('abcdefgh'); + * + * $size = 10 * 1024; + * $plaintext = ''; + * for ($i = 0; $i < $size; $i++) { + * $plaintext.= 'a'; + * } + * + * echo $des->decrypt($des->encrypt($plaintext)); + * ?> + * + * + * LICENSE: This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + * + * @category Crypt + * @package Crypt_DES + * @author Jim Wigginton + * @copyright MMVII Jim Wigginton + * @license http://www.gnu.org/licenses/lgpl.txt + * @version $Id: DES.php,v 1.1 2007-07-02 04:19:47 terrafrost Exp $ + * @link http://pear.php.net/package/Crypt_DES + */ + +/**#@+ + * @access private + * @see Crypt_DES::_prepareKey() + * @see Crypt_DES::_processBlock() + */ +/** + * Contains array_reverse($keys[CRYPT_DES_DECRYPT]) + */ +define('CRYPT_DES_ENCRYPT', 0); +/** + * Contains array_reverse($keys[CRYPT_DES_ENCRYPT]) + */ +define('CRYPT_DES_DECRYPT', 1); +/**#@-*/ + +/**#@+ + * @access public + * @see Crypt_DES::encrypt() + * @see Crypt_DES::decrypt() + */ +/** + * Encrypt / decrypt using the Electronic Code Book mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29 + */ +define('CRYPT_DES_MODE_ECB', 1); +/** + * Encrypt / decrypt using the Code Book Chaining mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29 + */ +define('CRYPT_DES_MODE_CBC', 2); +/**#@-*/ + +/**#@+ + * @access private + * @see Crypt_DES::Crypt_DES() + */ +/** + * Toggles the internal implementation + */ +define('CRYPT_DES_MODE_INTERNAL', 1); +/** + * Toggles the mcrypt implementation + */ +define('CRYPT_DES_MODE_MCRYPT', 2); +/**#@-*/ + +/** + * Pure-PHP implementation of DES. + * + * @author Jim Wigginton + * @version 0.1.0 + * @access public + * @package Crypt_DES + */ +class Crypt_DES { + /** + * The Key Schedule + * + * @see Crypt_DES::setKey() + * @var Array + * @access private + */ + var $keys = false; + + /** + * The Encryption Mode + * + * @see Crypt_DES::Crypt_DES() + * @var Integer + * @access private + */ + var $mode; + + /** + * Continuous Buffer status + * + * @see Crypt_DES::enableContinuousBuffer() + * @var Boolean + * @access private + */ + var $continuousBuffer = false; + + /** + * Padding status + * + * @see Crypt_DES::enablePadding() + * @var Boolean + * @access private + */ + var $padding = true; + + /** + * The Initialization Vector + * + * @see Crypt_DES::setIV() + * @var Integer + * @access private + */ + var $iv = "\0\0\0\0\0\0\0\0"; + + /** + * A "sliding" Initialization Vector + * + * @see Crypt_DES::enableContinuousBuffer() + * @var Integer + * @access private + */ + var $encryptIV = "\0\0\0\0\0\0\0\0"; + + /** + * A "sliding" Initialization Vector + * + * @see Crypt_DES::enableContinuousBuffer() + * @var Integer + * @access private + */ + var $decryptIV = "\0\0\0\0\0\0\0\0"; + + /** + * MCrypt parameters + * + * @see Crypt_DES::setMCrypt() + * @var Array + * @access private + */ + var $mcrypt = array('', ''); + + /** + * Default Constructor. + * + * Determines whether or not the mcrypt extension should be used. $mode should only, at present, be + * CRYPT_DES_MODE_ECB or CRYPT_DES_MODE_CBC. If not explictly set, CRYPT_DES_MODE_CBC will be used. + * + * @param optional Integer $mode + * @return Crypt_DES + * @access public + */ + function Crypt_DES($mode = CRYPT_MODE_DES_CBC) + { + if ( !defined('CRYPT_DES_MODE') ) { + switch (true) { + case extension_loaded('mcrypt'): + // i'd check to see if des was supported, by doing in_array('des', mcrypt_list_algorithms('')), + // but since that can be changed after the object has been created, there doesn't seem to be + // a lot of point... + define('CRYPT_DES_MODE', CRYPT_DES_MODE_MCRYPT); + break; + default: + define('CRYPT_DES_MODE', CRYPT_DES_MODE_INTERNAL); + } + } + + switch ( CRYPT_DES_MODE ) { + case CRYPT_DES_MODE_MCRYPT: + switch ($mode) { + case CRYPT_DES_MODE_ECB: + $this->mode = MCRYPT_MODE_ECB; break; + case CRYPT_DES_MODE_CBC: + default: + $this->mode = MCRYPT_MODE_CBC; + } + + break; + default: + switch ($mode) { + case CRYPT_DES_MODE_ECB: + case CRYPT_DES_MODE_CBC: + $this->mode = $mode; + break; + default: + $this->mode = CRYPT_DES_MODE_CBC; + } + } + } + + /** + * Sets the key. + * + * Keys can be of any length. DES, itself, uses 64-bit keys (eg. strlen($key) == 8), however, we + * only use the first eight, if $key has more then eight characters in it, and pad $key with the + * null byte if it is less then eight characters long. + * + * DES also requires that every eighth bit be a parity bit, however, we'll ignore that. + * + * If the key is not explicitly set, it'll be assumed to be all zero's. + * + * @access public + * @param String $key + */ + function setKey($key) + { + $this->keys = ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) ? substr($key, 0, 8) : $this->_prepareKey($key); + } + + /** + * Sets the initialization vector. (optional) + * + * SetIV is not required when CRYPT_DES_MODE_ECB is being used. If not explictly set, it'll be assumed + * to be all zero's. + * + * @access public + * @param String $iv + */ + function setIV($iv) + { + $this->iv = str_pad(substr($iv, 0, 8), 8, chr(0));; + } + + /** + * Sets MCrypt parameters. (optional) + * + * If MCrypt is being used, empty strings will be used, unless otherwise specified. + * + * @link http://php.net/function.mcrypt-module-open#function.mcrypt-module-open + * @access public + * @param Integer $algorithm_directory + * @param Integer $mode_directory + */ + function setMCrypt($algorithm_directory, $mode_directory) + { + $this->mcrypt = array($algorithm_directory, $mode_directory); + } + + /** + * Encrypts a message. + * + * $plaintext will be padded with up to 8 additional bytes. Other DES implementations may or may not pad in the + * same manner. Other common approaches to padding and the reasons why it's necessary are discussed in the following + * URL: + * + * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html} + * + * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does. + * strlen($plaintext) will still need to be a multiple of 8, however, arbitrary values can be added to make it that + * length. + * + * @see Crypt_DES::decrypt() + * @access public + * @param String $plaintext + */ + function encrypt($plaintext) + { + $this->_pad($plaintext); + + if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) { + $td = mcrypt_module_open(MCRYPT_DES, $this->mcrypt[0], $this->mode, $this->mcrypt[1]); + mcrypt_generic_init($td, $this->keys, $this->encryptIV); + + $ciphertext = mcrypt_generic($td, $plaintext); + + mcrypt_generic_deinit($td); + mcrypt_module_close($td); + + if ($this->continuousBuffer) { + $this->encryptIV = substr($ciphertext, -8); + } + + return $ciphertext; + } + + if ($this->keys === false) { + $this->keys = $this->_prepareKey("\0\0\0\0\0\0\0\0"); + } + + $ciphertext = ''; + switch ($this->mode) { + case CRYPT_DES_MODE_ECB: + for ($i = 0; $i < strlen($plaintext); $i+=8) { + $ciphertext.= $this->_processBlock(substr($plaintext, $i, 8), CRYPT_DES_ENCRYPT); + } + break; + case CRYPT_DES_MODE_CBC: + $xor = $this->encryptIV; + for ($i = 0; $i < strlen($plaintext); $i+=8) { + $block = substr($plaintext, $i, 8); + $block = $this->_processBlock($block ^ $xor, CRYPT_DES_ENCRYPT); + $xor = $block; + $ciphertext.= $block; + } + if ($this->continuousBuffer) { + $this->encryptIV = $xor; + } + } + + return $ciphertext; + } + + /** + * Decrypts a message. + * + * If strlen($ciphertext) is not a multiple of 8, null bytes will be added to the end of the string until it is. + * + * @see Crypt_DES::encrypt() + * @access public + * @param String $ciphertext + */ + function decrypt($ciphertext) + { + // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic : + // "The data is padded with "\0" to make sure the length of the data is n * blocksize." + $ciphertext = str_pad($ciphertext, (strlen($ciphertext) + 7) & 0xFFFFFFF8, chr(0)); + + if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) { + $td = mcrypt_module_open(MCRYPT_DES, $this->mcrypt[0], $this->mode, $this->mcrypt[1]); + mcrypt_generic_init($td, $this->keys, $this->decryptIV); + + $plaintext = mdecrypt_generic($td, $ciphertext); + + mcrypt_generic_deinit($td); + mcrypt_module_close($td); + + if ($this->continuousBuffer) { + $this->decryptIV = substr($ciphertext, -8); + } + + return $this->_unpad($plaintext); + } + + if ($this->keys === false) { + $this->keys = $this->_prepareKey("\0\0\0\0\0\0\0\0"); + } + + $plaintext = ''; + switch ($this->mode) { + case CRYPT_DES_MODE_ECB: + for ($i = 0; $i < strlen($ciphertext); $i+=8) { + $plaintext.= $this->_processBlock(substr($ciphertext, $i, 8), CRYPT_DES_DECRYPT); + } + break; + case CRYPT_DES_MODE_CBC: + $xor = $this->decryptIV; + for ($i = 0; $i < strlen($ciphertext); $i+=8) { + $block = substr($ciphertext, $i, 8); + $plaintext.= $this->_processBlock($block, CRYPT_DES_DECRYPT) ^ $xor; + $xor = $block; + } + if ($this->continuousBuffer) { + $this->decryptIV = $xor; + } + } + + return $this->_unpad($plaintext); + } + + /** + * Treat consecutive "packets" as if they are a continuous buffer. + * + * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets + * will yield different outputs: + * + * + * echo $des->encrypt(substr($plaintext, 0, 8)); + * echo $des->encrypt(substr($plaintext, 8, 8)); + * + * + * echo $des->encrypt($plaintext); + * + * + * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates + * another, as demonstrated with the following: + * + * + * $des->encrypt(substr($plaintext, 0, 8)); + * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8))); + * + * + * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8))); + * + * + * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different + * outputs. The reason is due to the fact that the initialization vector's change after every encryption / + * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant. + * + * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each + * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that + * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them), + * however, they are also less intuitive and more likely to cause you problems. + * + * @see Crypt_DES::disableContinuousBuffer() + * @access public + */ + function enableContinuousBuffer() + { + $this->continuousBuffer = true; + } + + /** + * Treat consecutive packets as if they are a discontinuous buffer. + * + * The default behavior. + * + * @see Crypt_DES::enableContinuousBuffer() + * @access public + */ + function disableContinuousBuffer() + { + $this->continuousBuffer = false; + $this->encryptIV = $this->iv; + $this->decryptIV = $this->iv; + } + + /** + * Pad "packets". + * + * DES works by encrypting eight bytes at a time. If you ever need to encrypt or decrypt something that's not + * a multiple of eight, it becomes necessary to pad the input so that it's length is a multiple of eight. + * + * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH1, + * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping + * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is + * transmitted separately) + * + * @see Crypt_DES::disablePadding() + * @access public + */ + function enablePadding() + { + $this->padding = true; + } + + /** + * Do not pad packets. + * + * @see Crypt_DES::enablePadding() + * @access public + */ + function disablePadding() + { + $this->padding = false; + } + + /** + * Pads a string + * + * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize (8). + * 8 - (strlen($text) & 7) bytes are added, each of which is equal to chr(8 - (strlen($text) & 7) + * + * @see Crypt_DES::_unpad() + * @access private + */ + function _pad($text) + { + if (!$this->padding) { + return $text; + } + + $length = 8 - (strlen($text) & 7); + return str_pad($text, strlen($text) + $length, chr($length)); + } + + /** + * Unpads a string + * + * @see Crypt_DES::_pad() + * @access private + */ + function _unpad($text) + { + if (!$this->padding) { + return $text; + } + + $length = ord($text{strlen($text) - 1}); + return substr($text, 0, -$length); + } + + /** + * Encrypts or decrypts a 64-bit block + * + * $mode should be either CRYPT_DES_ENCRYPT or CRYPT_DES_DECRYPT. See + * {@link http://en.wikipedia.org/wiki/Image:Feistel.png Feistel.png} to get a general + * idea of what this function does. + * + * @access private + * @param String $block + * @param Integer $mode + * @return String + */ + function _processBlock($block, $mode) + { + // s-boxes. in the official DES docs, they're described as being matrices that + // one accesses by using the first and last bits to determine the row and the + // middle four bits to determine the column. in this implementation, they've + // been converted to vectors + static $sbox = array( + array( + 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1, + 3, 10 ,10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8, + 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7, + 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13 + ), + array( + 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14, + 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5, + 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2, + 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9 + ), + array( + 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10, + 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1, + 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7, + 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12 + ), + array( + 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3, + 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9, + 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8, + 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14 + ), + array( + 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1, + 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6, + 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13, + 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3 + ), + array( + 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5, + 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8, + 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10, + 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13 + ), + array( + 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10, + 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6, + 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7, + 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12 + ), + array( + 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4, + 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2, + 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13, + 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11 + ) + ); + + $temp = unpack('Na/Nb', $block); + $block = array($temp['a'], $temp['b']); + + // because php does arithmetic right shifts, if the most significant bits are set, right + // shifting those into the correct position will add 1's - not 0's. this will intefere + // with the | operation unless a second & is done. so we isolate these bits and left shift + // them into place. we then & each block with 0x7FFFFFFF to prevennt 1's from being added + // for any other shifts. + $msb = array( + ($block[0] >> 31) & 1, + ($block[1] >> 31) & 1 + ); + $block[0] &= 0x7FFFFFFF; + $block[1] &= 0x7FFFFFFF; + + // we isolate the appropriate bit in the appropriate integer and shift as appropriate. in + // some cases, there are going to be multiple bits in the same integer that need to be shifted + // in the same way. we combine those into one shift operation. + $block = array( + (($block[1] & 0x00000040) << 25) | (($block[1] & 0x00004000) << 16) | + (($block[1] & 0x00400001) << 7) | (($block[1] & 0x40000100) >> 2) | + (($block[0] & 0x00000040) << 21) | (($block[0] & 0x00004000) << 12) | + (($block[0] & 0x00400001) << 3) | (($block[0] & 0x40000100) >> 6) | + (($block[1] & 0x00000010) << 19) | (($block[1] & 0x00001000) << 10) | + (($block[1] & 0x00100000) << 1) | (($block[1] & 0x10000000) >> 8) | + (($block[0] & 0x00000010) << 15) | (($block[0] & 0x00001000) << 6) | + (($block[0] & 0x00100000) >> 3) | (($block[0] & 0x10000000) >> 12) | + (($block[1] & 0x00000004) << 13) | (($block[1] & 0x00000400) << 4) | + (($block[1] & 0x00040000) >> 5) | (($block[1] & 0x04000000) >> 14) | + (($block[0] & 0x00000004) << 9) | ( $block[0] & 0x00000400 ) | + (($block[0] & 0x00040000) >> 9) | (($block[0] & 0x04000000) >> 18) | + (($block[1] & 0x00010000) >> 11) | (($block[1] & 0x01000000) >> 20) | + (($block[0] & 0x00010000) >> 15) | (($block[0] & 0x01000000) >> 24) + , + (($block[1] & 0x00000080) << 24) | (($block[1] & 0x00008000) << 15) | + (($block[1] & 0x00800002) << 6) | (($block[0] & 0x00000080) << 20) | + (($block[0] & 0x00008000) << 11) | (($block[0] & 0x00800002) << 2) | + (($block[1] & 0x00000020) << 18) | (($block[1] & 0x00002000) << 9) | + ( $block[1] & 0x00200000 ) | (($block[1] & 0x20000000) >> 9) | + (($block[0] & 0x00000020) << 14) | (($block[0] & 0x00002000) << 5) | + (($block[0] & 0x00200000) >> 4) | (($block[0] & 0x20000000) >> 13) | + (($block[1] & 0x00000008) << 12) | (($block[1] & 0x00000800) << 3) | + (($block[1] & 0x00080000) >> 6) | (($block[1] & 0x08000000) >> 15) | + (($block[0] & 0x00000008) << 8) | (($block[0] & 0x00000800) >> 1) | + (($block[0] & 0x00080000) >> 10) | (($block[0] & 0x08000000) >> 19) | + (($block[1] & 0x00000200) >> 3) | (($block[0] & 0x00000200) >> 7) | + (($block[1] & 0x00020000) >> 12) | (($block[1] & 0x02000000) >> 21) | + (($block[0] & 0x00020000) >> 16) | (($block[0] & 0x02000000) >> 25) | + ($msb[1] << 28) | ($msb[0] << 24) + ); + + for ($i = 0; $i < 16; $i++) { + // start of "the Feistel (F) function" - see the following URL: + // http://en.wikipedia.org/wiki/Image:Data_Encryption_Standard_InfoBox_Diagram.png + $temp = (($sbox[0][((($block[1] >> 27) & 0x1F) | (($block[1] & 1) << 5)) ^ $this->keys[$mode][$i][0]]) << 28) + | (($sbox[1][(($block[1] & 0x1F800000) >> 23) ^ $this->keys[$mode][$i][1]]) << 24) + | (($sbox[2][(($block[1] & 0x01F80000) >> 19) ^ $this->keys[$mode][$i][2]]) << 20) + | (($sbox[3][(($block[1] & 0x001F8000) >> 15) ^ $this->keys[$mode][$i][3]]) << 16) + | (($sbox[4][(($block[1] & 0x0001F800) >> 11) ^ $this->keys[$mode][$i][4]]) << 12) + | (($sbox[5][(($block[1] & 0x00001F80) >> 7) ^ $this->keys[$mode][$i][5]]) << 8) + | (($sbox[6][(($block[1] & 0x000001F8) >> 3) ^ $this->keys[$mode][$i][6]]) << 4) + | ( $sbox[7][((($block[1] & 0x1F) << 1) | (($block[1] >> 31) & 1)) ^ $this->keys[$mode][$i][7]]); + + $msb = ($temp >> 31) & 1; + $temp &= 0x7FFFFFFF; + $newBlock = (($temp & 0x00010000) << 15) | (($temp & 0x02020120) << 5) + | (($temp & 0x00001800) << 17) | (($temp & 0x01000000) >> 10) + | (($temp & 0x00000008) << 24) | (($temp & 0x00100000) << 6) + | (($temp & 0x00000010) << 21) | (($temp & 0x00008000) << 9) + | (($temp & 0x00000200) << 12) | (($temp & 0x10000000) >> 27) + | (($temp & 0x00000040) << 14) | (($temp & 0x08000000) >> 8) + | (($temp & 0x00004000) << 4) | (($temp & 0x00000002) << 16) + | (($temp & 0x00442000) >> 6) | (($temp & 0x40800000) >> 15) + | (($temp & 0x00000001) << 11) | (($temp & 0x20000000) >> 20) + | (($temp & 0x00080000) >> 13) | (($temp & 0x00000004) << 3) + | (($temp & 0x04000000) >> 22) | (($temp & 0x00000480) >> 7) + | (($temp & 0x00200000) >> 19) | ($msb << 23); + // end of "the Feistel (F) function" - $newBlock is F's output + + $temp = $block[1]; + $block[1] = $block[0] ^ $newBlock; + $block[0] = $temp; + } + + $msb = array( + ($block[0] >> 31) & 1, + ($block[1] >> 31) & 1 + ); + $block[0] &= 0x7FFFFFFF; + $block[1] &= 0x7FFFFFFF; + + $block = array( + (($block[0] & 0x01000004) << 7) | (($block[1] & 0x01000004) << 6) | + (($block[0] & 0x00010000) << 13) | (($block[1] & 0x00010000) << 12) | + (($block[0] & 0x00000100) << 19) | (($block[1] & 0x00000100) << 18) | + (($block[0] & 0x00000001) << 25) | (($block[1] & 0x00000001) << 24) | + (($block[0] & 0x02000008) >> 2) | (($block[1] & 0x02000008) >> 3) | + (($block[0] & 0x00020000) << 4) | (($block[1] & 0x00020000) << 3) | + (($block[0] & 0x00000200) << 10) | (($block[1] & 0x00000200) << 9) | + (($block[0] & 0x00000002) << 16) | (($block[1] & 0x00000002) << 15) | + (($block[0] & 0x04000000) >> 11) | (($block[1] & 0x04000000) >> 12) | + (($block[0] & 0x00040000) >> 5) | (($block[1] & 0x00040000) >> 6) | + (($block[0] & 0x00000400) << 1) | ( $block[1] & 0x00000400 ) | + (($block[0] & 0x08000000) >> 20) | (($block[1] & 0x08000000) >> 21) | + (($block[0] & 0x00080000) >> 14) | (($block[1] & 0x00080000) >> 15) | + (($block[0] & 0x00000800) >> 8) | (($block[1] & 0x00000800) >> 9) + , + (($block[0] & 0x10000040) << 3) | (($block[1] & 0x10000040) << 2) | + (($block[0] & 0x00100000) << 9) | (($block[1] & 0x00100000) << 8) | + (($block[0] & 0x00001000) << 15) | (($block[1] & 0x00001000) << 14) | + (($block[0] & 0x00000010) << 21) | (($block[1] & 0x00000010) << 20) | + (($block[0] & 0x20000080) >> 6) | (($block[1] & 0x20000080) >> 7) | + ( $block[0] & 0x00200000 ) | (($block[1] & 0x00200000) >> 1) | + (($block[0] & 0x00002000) << 6) | (($block[1] & 0x00002000) << 5) | + (($block[0] & 0x00000020) << 12) | (($block[1] & 0x00000020) << 11) | + (($block[0] & 0x40000000) >> 15) | (($block[1] & 0x40000000) >> 16) | + (($block[0] & 0x00400000) >> 9) | (($block[1] & 0x00400000) >> 10) | + (($block[0] & 0x00004000) >> 3) | (($block[1] & 0x00004000) >> 4) | + (($block[0] & 0x00800000) >> 18) | (($block[1] & 0x00800000) >> 19) | + (($block[0] & 0x00008000) >> 12) | (($block[1] & 0x00008000) >> 13) | + ($msb[0] << 7) | ($msb[1] << 6) + ); + + return pack('NN', $block[0], $block[1]); + } + + /** + * Creates the key schedule. + * + * @access private + * @param String $key + * @return Array + */ + function _prepareKey($key) + { + static $shifts = array( // number of key bits shifted per round + 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 + ); + + // pad the key and remove extra characters as appropriate. + $key = str_pad(substr($key, 0, 8), 8, chr(0)); + + $temp = unpack('Na/Nb', $key); + $key = array($temp['a'], $temp['b']); + $msb = array( + ($key[0] >> 31) & 1, + ($key[1] >> 31) & 1 + ); + $key[0] &= 0x7FFFFFFF; + $key[1] &= 0x7FFFFFFF; + + $key = array( + (($key[1] & 0x00000002) << 26) | (($key[1] & 0x00000204) << 17) | + (($key[1] & 0x00020408) << 8) | (($key[1] & 0x02040800) >> 1) | + (($key[0] & 0x00000002) << 22) | (($key[0] & 0x00000204) << 13) | + (($key[0] & 0x00020408) << 4) | (($key[0] & 0x02040800) >> 5) | + (($key[1] & 0x04080000) >> 10) | (($key[0] & 0x04080000) >> 14) | + (($key[1] & 0x08000000) >> 19) | (($key[0] & 0x08000000) >> 23) | + (($key[0] & 0x00000010) >> 1) | (($key[0] & 0x00001000) >> 10) | + (($key[0] & 0x00100000) >> 19) | (($key[0] & 0x10000000) >> 28) + , + (($key[1] & 0x00000080) << 20) | (($key[1] & 0x00008000) << 11) | + (($key[1] & 0x00800000) << 2) | (($key[0] & 0x00000080) << 16) | + (($key[0] & 0x00008000) << 7) | (($key[0] & 0x00800000) >> 2) | + (($key[1] & 0x00000040) << 13) | (($key[1] & 0x00004000) << 4) | + (($key[1] & 0x00400000) >> 5) | (($key[1] & 0x40000000) >> 14) | + (($key[0] & 0x00000040) << 9) | ( $key[0] & 0x00004000 ) | + (($key[0] & 0x00400000) >> 9) | (($key[0] & 0x40000000) >> 18) | + (($key[1] & 0x00000020) << 6) | (($key[1] & 0x00002000) >> 3) | + (($key[1] & 0x00200000) >> 12) | (($key[1] & 0x20000000) >> 21) | + (($key[0] & 0x00000020) << 2) | (($key[0] & 0x00002000) >> 7) | + (($key[0] & 0x00200000) >> 16) | (($key[0] & 0x20000000) >> 25) | + (($key[1] & 0x00000010) >> 1) | (($key[1] & 0x00001000) >> 10) | + (($key[1] & 0x00100000) >> 19) | (($key[1] & 0x10000000) >> 28) | + ($msb[1] << 24) | ($msb[0] << 20) + ); + + $keys = array(); + for ($i = 0; $i < 16; $i++) { + $key[0] <<= $shifts[$i]; + $temp = ($key[0] & 0xF0000000) >> 28; + $key[0] = ($key[0] | $temp) & 0x0FFFFFFF; + + $key[1] <<= $shifts[$i]; + $temp = ($key[1] & 0xF0000000) >> 28; + $key[1] = ($key[1] | $temp) & 0x0FFFFFFF; + + $temp = array(0, 0); + for ($j = 0; $j < 48; $j++) { + $bitmasked = $key[floor($ki[$j] / 28)] & (1 << ($ki[$j] % 28)); + $shift = 5 - ($j % 6); + $temp[floor($j / 6)] |= ($bitmasked != 0) << $shift; + } + + $temp = array( + (($key[1] & 0x00004000) >> 9) | (($key[1] & 0x00000800) >> 7) | + (($key[1] & 0x00020000) >> 14) | (($key[1] & 0x00000010) >> 2) | + (($key[1] & 0x08000000) >> 26) | (($key[1] & 0x00800000) >> 23) + , + (($key[1] & 0x02400000) >> 20) | (($key[1] & 0x00000001) << 4) | + (($key[1] & 0x00002000) >> 10) | (($key[1] & 0x00040000) >> 18) | + (($key[1] & 0x00000080) >> 6) + , + ( $key[1] & 0x00000020 ) | (($key[1] & 0x00000200) >> 5) | + (($key[1] & 0x00010000) >> 13) | (($key[1] & 0x01000000) >> 22) | + (($key[1] & 0x00000004) >> 1) | (($key[1] & 0x00100000) >> 20) + , + (($key[1] & 0x00001000) >> 7) | (($key[1] & 0x00200000) >> 17) | + (($key[1] & 0x00000002) << 2) | (($key[1] & 0x00000100) >> 6) | + (($key[1] & 0x00008000) >> 14) | (($key[1] & 0x04000000) >> 26) + , + (($key[0] & 0x00008000) >> 10) | ( $key[0] & 0x00000010 ) | + (($key[0] & 0x02000000) >> 22) | (($key[0] & 0x00080000) >> 17) | + (($key[0] & 0x00000200) >> 8) | (($key[0] & 0x00000002) >> 1) + , + (($key[0] & 0x04000000) >> 21) | (($key[0] & 0x00010000) >> 12) | + (($key[0] & 0x00000020) >> 2) | (($key[0] & 0x00000800) >> 9) | + (($key[0] & 0x00800000) >> 22) | (($key[0] & 0x00000100) >> 8) + , + (($key[0] & 0x00001000) >> 7) | (($key[0] & 0x00000088) >> 3) | + (($key[0] & 0x00020000) >> 14) | (($key[0] & 0x00000001) << 2) | + (($key[0] & 0x00400000) >> 21) + , + (($key[0] & 0x00000400) >> 5) | (($key[0] & 0x00004000) >> 10) | + (($key[0] & 0x00000040) >> 3) | (($key[0] & 0x00100000) >> 18) | + (($key[0] & 0x08000000) >> 26) | (($key[0] & 0x01000000) >> 24) + ); + + $keys[] = $temp; + } + + $temp = array( + CRYPT_DES_ENCRYPT => $keys, + CRYPT_DES_DECRYPT => array_reverse($keys) + ); + + return $temp; + } +} + +// vim: ts=4:sw=4:et: +// vim6: fdl=1: +?> \ No newline at end of file diff --git a/phpseclib/Crypt/RC4.php b/phpseclib/Crypt/RC4.php new file mode 100644 index 00000000..99680e18 --- /dev/null +++ b/phpseclib/Crypt/RC4.php @@ -0,0 +1,421 @@ + + * setKey('abcdefgh'); + * + * $size = 10 * 1024; + * $plaintext = ''; + * for ($i = 0; $i < $size; $i++) { + * $plaintext.= 'a'; + * } + * + * echo $rc4->decrypt($rc4->encrypt($plaintext)); + * ?> + * + * + * LICENSE: This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + * + * @category Crypt + * @package Crypt_RC4 + * @author Jim Wigginton + * @copyright MMVII Jim Wigginton + * @license http://www.gnu.org/licenses/lgpl.txt + * @version $Id: RC4.php,v 1.1 2007-07-02 04:19:47 terrafrost Exp $ + * @link http://pear.php.net/package/Crypt_RC4 + */ + +/**#@+ + * @access private + * @see Crypt_RC4::Crypt_RC4() + */ +/** + * Toggles the internal implementation + */ +define('CRYPT_RC4_MODE_INTERNAL', 1); +/** + * Toggles the mcrypt implementation + */ +define('CRYPT_RC4_MODE_MCRYPT', 2); +/**#@-*/ + +/**#@+ + * @access private + * @see Crypt_RC4::_crypt() + */ +define('CRYPT_RC4_ENCRYPT', 0); +define('CRYPT_RC4_DECRYPT', 1); +/**#@-*/ + +/** + * Pure-PHP implementation of RC4. + * + * @author Jim Wigginton + * @version 0.1.0 + * @access public + * @package Crypt_RC4 + */ +class Crypt_RC4 { + /** + * The Key + * + * @see Crypt_RC4::setKey() + * @var String + * @access private + */ + var $key = "\0"; + + /** + * The Key Stream for encryption + * + * If CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT, this will be equal to the mcrypt object + * + * @see Crypt_RC4::setKey() + * @var Array + * @access private + */ + var $encryptStream = false; + + /** + * The Key Stream for decryption + * + * If CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT, this will be equal to the mcrypt object + * + * @see Crypt_RC4::setKey() + * @var Array + * @access private + */ + var $decryptStream = false; + + /** + * The $i and $j indexes for encryption + * + * @see Crypt_RC4::_crypt() + * @var Integer + * @access private + */ + var $encryptIndex = 0; + + /** + * The $i and $j indexes for decryption + * + * @see Crypt_RC4::_crypt() + * @var Integer + * @access private + */ + var $decryptIndex = 0; + + /** + * The Encryption Algorithm + * + * Only used if CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT. Only possible values are MCRYPT_RC4 or MCRYPT_ARCFOUR. + * + * @see Crypt_RC4::Crypt_RC4() + * @var Integer + * @access private + */ + var $mode; + + /** + * Default Constructor. + * + * Determines whether or not the mcrypt extension should be used. + * + * @param optional Integer $mode + * @return Crypt_RC4 + * @access public + */ + function Crypt_RC4() + { + if ( !defined('CRYPT_RC4_MODE') ) { + switch (true) { + case extension_loaded('mcrypt') && (defined('MCRYPT_ARCFOUR') || defined('MCRYPT_RC4')): + // i'd check to see if rc4 was supported, by doing in_array('arcfour', mcrypt_list_algorithms('')), + // but since that can be changed after the object has been created, there doesn't seem to be + // a lot of point... + define('CRYPT_RC4_MODE', CRYPT_RC4_MODE_MCRYPT); + switch (true) { + case defined('MCRYPT_ARCFOUR'): + $this->mode = MCRYPT_ARCFOUR; + break; + case defined('MCRYPT_RC4'); + $this->mode = MCRYPT_RC4; + } + $this->encryptStream = @mcrypt_module_open($this->mode, '', MCRYPT_MODE_STREAM, ''); + $this->decryptStream = @mcrypt_module_open($this->mode, '', MCRYPT_MODE_STREAM, ''); + break; + default: + define('CRYPT_RC4_MODE', CRYPT_RC4_MODE_INTERNAL); + } + } + } + + /** + * Sets the key. + * + * Keys can be between 1 and 256 bytes long. If they are longer then 256 bytes, the first 256 bytes will + * be used. If no key is explicitly set, it'll be assumed to be a single null byte. Some protocols, such + * as WEP, prepend an "initialization vector" to the key, effectively creating a new key [1]. If you need + * to use an initialization vector in this manner, feel free to preend it to the key, yourself, before + * calling this function. + * + * [1] WEP's initialization vectors (IV's) are used in a somewhat insecure way. Since, in that protocol, + * the IV's are relatively easy to predict, an attack described by + * {@link http://www.drizzle.com/~aboba/IEEE/rc4_ksaproc.pdf Scott Fluhrer, Itsik Mantin, and Adi Shamir} + * can be used to quickly guess at the rest of the key. The following links elaborate: + * + * {@link http://www.rsa.com/rsalabs/node.asp?id=2009 http://www.rsa.com/rsalabs/node.asp?id=2009} + * {@link http://en.wikipedia.org/wiki/Related_key_attack http://en.wikipedia.org/wiki/Related_key_attack} + * + * @access public + * @param String $key + */ + function setKey($key) + { + $this->key = $key; + + if (CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT) { + return; + } + + $keyLength = strlen($key); + $keyStream = array(); + for ($i = 0; $i < 256; $i++) { + $keyStream[$i] = $i; + } + $j = 0; + for ($i = 0; $i < 256; $i++) { + $j = ($j + $keyStream[$i] + ord($key[$i % $keyLength])) & 255; + $keyStream[$i] ^= $keyStream[$j]; + $keyStream[$j] ^= $keyStream[$i]; + $keyStream[$i] ^= $keyStream[$j]; + } + + $this->encryptIndex = $this->decryptIndex = array(0, 0); + $this->encryptStream = $this->decryptStream = $keyStream; + } + + /** + * Sets MCrypt parameters. (optional) + * + * If MCrypt is being used, empty strings will be used, unless otherwise specified. + * + * @link http://php.net/function.mcrypt-module-open#function.mcrypt-module-open + * @access public + * @param Integer $algorithm_directory + * @param Integer $mode_directory + */ + function setMCrypt($algorithm_directory, $mode_directory) + { + $this->encryptStream = @mcrypt_module_open($this->mode, $algorithm_directory, MCRYPT_MODE_STREAM, $mode_directory); + $this->decryptStream = @mcrypt_module_open($this->mode, $algorithm_directory, MCRYPT_MODE_STREAM, $mode_directory); + } + + /** + * Encrypts a message. + * + * @see Crypt_RC4::_crypt() + * @access public + * @param String $plaintext + */ + function encrypt($plaintext) { + return $this->_crypt($plaintext, CRYPT_RC4_ENCRYPT); + } + + /** + * Decrypts a message. + * + * $this->decrypt($this->encrypt($plaintext)) == $this->encrypt($this->encrypt($plaintext)). + * Atleast if the continuous buffer is disabled. + * + * @see Crypt_RC4::_crypt() + * @access public + * @param String $ciphertext + */ + function decrypt($ciphertext) { + return $this->_crypt($ciphertext, CRYPT_RC4_DECRYPT); + } + + /** + * Encrypts or decrypts a message. + * + * @see Crypt_RC4::encrypt() + * @see Crypt_RC4::decrypt() + * @access private + * @param String $text + * @param Integer $mode + */ + function _crypt($text, $mode) { + switch ($mode) { + case CRYPT_RC4_ENCRYPT: + $keyStream = $this->encryptStream; + list($i, $j) = $this->encryptIndex; + break; + case CRYPT_RC4_DECRYPT: + $keyStream = $this->decryptStream; + list($i, $j) = $this->decryptIndex; + } + + if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) { + if (!$this->continuousBuffer) { + mcrypt_generic_init($keyStream, $this->key, ''); + } + $newText = mcrypt_generic($keyStream, $text); + if (!$this->continuousBuffer) { + mcrypt_generic_deinit($keyStream); + } + + return $newText; + } + + $newText = ''; + for ($k = 0; $k < strlen($text); $k++) { + $i = ($i + 1) & 255; + $j = ($j + $keyStream[$i]) & 255; + $keyStream[$i] ^= $keyStream[$j]; + $keyStream[$j] ^= $keyStream[$i]; + $keyStream[$i] ^= $keyStream[$j]; + $temp = $keyStream[($keyStream[$i] + $keyStream[$j]) & 255]; + $newText.= chr(ord($text[$k]) ^ $temp); + } + + if ($this->continuousBuffer) { + switch ($mode) { + case CRYPT_RC4_ENCRYPT: + $this->encryptStream = $keyStream; + $this->encryptIndex = array($i, $j); + break; + case CRYPT_RC4_DECRYPT: + $this->decryptStream = $keyStream; + $this->decryptIndex = array($i, $j); + } + } + + return $newText; + } + + /** + * Treat consecutive "packets" as if they are a continuous buffer. + * + * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets + * will yield different outputs: + * + * + * echo $rc4->encrypt(substr($plaintext, 0, 8)); + * echo $rc4->encrypt(substr($plaintext, 8, 8)); + * + * + * echo $rc4->encrypt($plaintext); + * + * + * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates + * another, as demonstrated with the following: + * + * + * $rc4->encrypt(substr($plaintext, 0, 8)); + * echo $rc4->decrypt($des->encrypt(substr($plaintext, 8, 8))); + * + * + * echo $rc4->decrypt($des->encrypt(substr($plaintext, 8, 8))); + * + * + * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different + * outputs. The reason is due to the fact that the initialization vector's change after every encryption / + * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant. + * + * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each + * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that + * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them), + * however, they are also less intuitive and more likely to cause you problems. + * + * @see Crypt_RC4::disableContinuousBuffer() + * @access public + */ + function enableContinuousBuffer() + { + if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) { + $this->encryptStream = mcrypt_module_open($this->mode, $this->mcrypt[0], MCRYPT_MODE_STREAM, $this->mcrypt[1]); + $this->decryptStream = mcrypt_module_open($this->mode, $this->mcrypt[0], MCRYPT_MODE_STREAM, $this->mcrypt[1]); + + mcrypt_generic_init($this->encryptStream, $this->key, ''); + mcrypt_generic_init($this->decryptStream, $this->key, ''); + } + + $this->continuousBuffer = true; + } + + /** + * Treat consecutive packets as if they are a discontinuous buffer. + * + * The default behavior. + * + * @see Crypt_RC4::enableContinuousBuffer() + * @access public + */ + function disableContinuousBuffer() + { + if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_INTERNAL ) { + $this->encryptIndex = $this->decryptIndex = array(0, 0); + $this->setKey($this->key); + } + + $this->continuousBuffer = false; + } + + /** + * Class destructor. + * + * Will be called, automatically, if you're using PHP5. If you're using PHP4, call it yourself. Only really + * needs to be called if mcrypt is being used. + * + * @access public + */ + function __destruct() { + if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT && isset($this->encryptStream) ) { + if ( $this->continuousBuffer ) { + mcrypt_generic_deinit($this->encryptStream); + mcrypt_generic_deinit($this->decryptStream); + } + + mcrypt_module_close($this->encryptStream); + mcrypt_module_close($this->decryptStream); + + unset($this->encryptStream); + unset($this->decryptStream); + } + } +} \ No newline at end of file diff --git a/phpseclib/Crypt/Random.php b/phpseclib/Crypt/Random.php new file mode 100644 index 00000000..5a8a72ab --- /dev/null +++ b/phpseclib/Crypt/Random.php @@ -0,0 +1,69 @@ + + * + * + * + * LICENSE: This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + * + * @category Crypt + * @package Crypt_Random + * @author Jim Wigginton + * @copyright MMVII Jim Wigginton + * @license http://www.gnu.org/licenses/lgpl.txt + * @version $Id: Random.php,v 1.1 2007-07-02 04:19:47 terrafrost Exp $ + * @link http://pear.php.net/package/Crypt_Random + */ + +/** + * Generate a random value. Feel free to replace this function with a cryptographically secure PRNG. + * + * @param optional Integer $min + * @param optional Integer $max + * @param optional String $randomness_path + * @return Integer + * @access public + */ +function crypt_random($min = 0, $max = 0x7FFFFFFF, $randomness_path = '/dev/urandom') +{ + static $seeded = false; + + if (!$seeded) { + $seeded = true; + if (file_exists($randomness_path)) { + $fp = fopen($randomness_path, 'r'); + mt_srand(pack('N', fread($fp, 4))); + fclose($fp); + } else { + list($sec, $usec) = explode(' ', microtime()); + mt_srand((float) $sec + ((float) $usec * 100000)); + } + } + + return mt_rand($min, $max); +} +?> \ No newline at end of file diff --git a/phpseclib/Crypt/TripleDES.php b/phpseclib/Crypt/TripleDES.php new file mode 100644 index 00000000..12756fc2 --- /dev/null +++ b/phpseclib/Crypt/TripleDES.php @@ -0,0 +1,564 @@ + + * setKey('abcdefghijklmnopqrstuvwx'); + * + * $size = 10 * 1024; + * $plaintext = ''; + * for ($i = 0; $i < $size; $i++) { + * $plaintext.= 'a'; + * } + * + * echo $des->decrypt($des->encrypt($plaintext)); + * ?> + * + * + * LICENSE: This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + * + * @category Crypt + * @package Crypt_TripleDES + * @author Jim Wigginton + * @copyright MMVII Jim Wigginton + * @license http://www.gnu.org/licenses/lgpl.txt + * @version $Id: TripleDES.php,v 1.1 2007-07-02 04:19:47 terrafrost Exp $ + * @link http://pear.php.net/package/Crypt_TripleDES + */ + +/** + * Include Crypt_DES + */ +require_once 'DES.php'; + +/** + * Encrypt / decrypt using a method required by SSHv1 + * + * mcrypt does a single XOR operation for each block in CBC mode. SSHv1 requires three XOR operations. + */ +define('CRYPT_DES_MODE_SSH', 3); + +/** + * Pure-PHP implementation of Triple DES. + * + * @author Jim Wigginton + * @version 0.1.0 + * @access public + * @package Crypt_DES + */ +class Crypt_TripleDES { + /** + * The Three Keys + * + * @see Crypt_TripleDES::setKey() + * @var String + * @access private + */ + var $key = "\0\0\0\0\0\0\0\0"; + + /** + * The Encryption Mode + * + * @see Crypt_TripleDES::Crypt_TripleDES() + * @var Integer + * @access private + */ + var $mode = CRYPT_DES_MODE_CBC; + + /** + * Continuous Buffer status + * + * @see Crypt_TripleDES::enableContinuousBuffer() + * @var Boolean + * @access private + */ + var $continuousBuffer = false; + + /** + * Padding status + * + * @see Crypt_TripleDES::enablePadding() + * @var Boolean + * @access private + */ + var $padding = true; + + /** + * The Initialization Vector + * + * @see Crypt_TripleDES::setIV() + * @var Integer + * @access private + */ + var $iv = "\0\0\0\0\0\0\0\0"; + + /** + * A "sliding" Initialization Vector + * + * @see Crypt_TripleDES::enableContinuousBuffer() + * @var Integer + * @access private + */ + var $encryptIV = "\0\0\0\0\0\0\0\0"; + + /** + * A "sliding" Initialization Vector + * + * @see Crypt_TripleDES::enableContinuousBuffer() + * @var Integer + * @access private + */ + var $decryptIV = "\0\0\0\0\0\0\0\0"; + + /** + * MCrypt parameters + * + * @see Crypt_TripleDES::setMCrypt() + * @var Array + * @access private + */ + var $mcrypt = array('', ''); + + /** + * The Crypt_DES objects + * + * @var Array + * @access private + */ + var $des; + + /** + * Default Constructor. + * + * Determines whether or not the mcrypt extension should be used. $mode should only, at present, be + * CRYPT_DES_MODE_ECB or CRYPT_DES_MODE_CBC. If not explictly set, CRYPT_DES_MODE_CBC will be used. + * + * @param optional Integer $mode + * @return Crypt_TripleDES + * @access public + */ + function Crypt_TripleDES($mode = CRYPT_DES_MODE_CBC) + { + if ( !defined('CRYPT_DES_MODE') ) { + switch (true) { + case extension_loaded('mcrypt'): + // i'd check to see if des was supported, by doing in_array('des', mcrypt_list_algorithms('')), + // but since that can be changed after the object has been created, there doesn't seem to be + // a lot of point... + define('CRYPT_DES_MODE', CRYPT_DES_MODE_MCRYPT); + break; + default: + define('CRYPT_DES_MODE', CRYPT_DES_MODE_INTERNAL); + } + } + + if ( $mode == CRYPT_DES_MODE_SSH ) { + $this->mode = CRYPT_DES_MODE_SSH; + $this->des = array( + new Crypt_DES(CRYPT_DES_MODE_CBC), + new Crypt_DES(CRYPT_DES_MODE_CBC), + new Crypt_DES(CRYPT_DES_MODE_CBC) + ); + return; + } + + switch ( CRYPT_DES_MODE ) { + case CRYPT_DES_MODE_MCRYPT: + switch ($mode) { + case CRYPT_DES_MODE_ECB: + $this->mode = MCRYPT_MODE_ECB; break; + case CRYPT_DES_MODE_CBC: + default: + $this->mode = MCRYPT_MODE_CBC; + } + + break; + default: + $this->des = array( + new Crypt_DES(CRYPT_DES_MODE_ECB), + new Crypt_DES(CRYPT_DES_MODE_ECB), + new Crypt_DES(CRYPT_DES_MODE_ECB) + ); + + switch ($mode) { + case CRYPT_DES_MODE_ECB: + case CRYPT_DES_MODE_CBC: + $this->mode = $mode; + break; + default: + $this->mode = CRYPT_DES_MODE_CBC; + } + } + } + + /** + * Sets the key. + * + * Keys can be of any length. Triple DES, itself, can use 128-bit (eg. strlen($key) == 16) or + * 192-bit (eg. strlen($key) == 24) keys. This function pads and truncates $key as appropriate. + * + * DES also requires that every eighth bit be a parity bit, however, we'll ignore that. + * + * If the key is not explicitly set, it'll be assumed to be all zero's. + * + * @access public + * @param String $key + */ + function setKey($key) + { + $length = strlen($key); + if ($length > 8) { + $key = str_pad($key, 24, chr(0)); + // if $key is between 64 and 128-bits, use the first 64-bits as the last, per this: + // http://php.net/function.mcrypt-encrypt#47973 + $key = $length <= 16 ? substr_replace($key, substr($key, 0, 8), 16) : $key; + } + $this->key = $key; + switch (true) { + case CRYPT_DES_MODE == CRYPT_DES_MODE_INTERNAL: + case $this->mode == CRYPT_DES_MODE_SSH: + $this->des[0]->setKey(substr($key, 0, 8)); + $this->des[1]->setKey(substr($key, 8, 8)); + $this->des[2]->setKey(substr($key, 16, 8)); + + // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects + $this->des[0]->disablePadding(); + $this->des[1]->disablePadding(); + $this->des[2]->disablePadding(); + } + + if ($this->mode == CRYPT_DES_MODE_SSH) { + $this->des[0]->enableContinuousBuffer(); + $this->des[1]->enableContinuousBuffer(); + $this->des[2]->enableContinuousBuffer(); + } + } + + /** + * Sets the initialization vector. (optional) + * + * SetIV is not required when CRYPT_DES_MODE_ECB is being used. If not explictly set, it'll be assumed + * to be all zero's. + * + * @access public + * @param String $iv + */ + function setIV($iv) + { + $this->iv = str_pad(substr($key, 0, 8), 8, chr(0));; + } + + /** + * Sets MCrypt parameters. (optional) + * + * If MCrypt is being used, empty strings will be used, unless otherwise specified. + * + * @link http://php.net/function.mcrypt-module-open#function.mcrypt-module-open + * @access public + * @param Integer $algorithm_directory + * @param Integer $mode_directory + */ + function setMCrypt($algorithm_directory, $mode_directory) + { + $this->mcrypt = array($algorithm_directory, $mode_directory); + if ( $this->mode == CRYPT_DES_MODE_SSH ) { + $this->des[0]->setMCrypt($algorithm_directory, $mode_directory); + $this->des[1]->setMCrypt($algorithm_directory, $mode_directory); + $this->des[2]->setMCrypt($algorithm_directory, $mode_directory); + } + } + + /** + * Encrypts a message. + * + * @access public + * @param String $plaintext + */ + function encrypt($plaintext) + { + // if the key is smaller then 8, do what we'd normally do + if ($this->mode == CRYPT_DES_MODE_SSH && strlen($this->key) > 8) { + $ciphertext = $this->des[2]->encrypt($this->des[1]->decrypt($this->des[0]->encrypt($plaintext))); + + return $ciphertext; + } + + if ($this->padding) { + $plaintext = $this->_pad($plaintext); + } + + if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) { + $td = mcrypt_module_open(MCRYPT_3DES, $this->mcrypt[0], $this->mode, $this->mcrypt[1]); + mcrypt_generic_init($td, $this->key, $this->encryptIV); + + $ciphertext = mcrypt_generic($td, $plaintext); + + mcrypt_generic_deinit($td); + mcrypt_module_close($td); + + if ($this->continuousBuffer) { + $this->encryptIV = substr($ciphertext, -8); + } + + return $ciphertext; + } + + if (strlen($this->key) <= 8) { + $this->des[0]->mode = $this->mode; + + return $this->des[0]->encrypt($plaintext); + } + + // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic : + // "The data is padded with "\0" to make sure the length of the data is n * blocksize." + $plaintext = str_pad($plaintext, ceil(strlen($plaintext) / 8) * 8, chr(0)); + + $ciphertext = ''; + switch ($this->mode) { + case CRYPT_DES_MODE_ECB: + for ($i = 0; $i < strlen($plaintext); $i+=8) { + $block = substr($plaintext, $i, 8); + $block = $this->des[0]->_processBlock($block, CRYPT_DES_ENCRYPT); + $block = $this->des[1]->_processBlock($block, CRYPT_DES_DECRYPT); + $block = $this->des[2]->_processBlock($block, CRYPT_DES_ENCRYPT); + $ciphertext.= $block; + } + break; + case CRYPT_DES_MODE_CBC: + $xor = $this->encryptIV; + for ($i = 0; $i < strlen($plaintext); $i+=8) { + $block = substr($plaintext, $i, 8) ^ $xor; + $block = $this->des[0]->_processBlock($block, CRYPT_DES_ENCRYPT); + $block = $this->des[1]->_processBlock($block, CRYPT_DES_DECRYPT); + $block = $this->des[2]->_processBlock($block, CRYPT_DES_ENCRYPT); + $xor = $block; + $ciphertext.= $block; + } + if ($this->continuousBuffer) { + $this->encryptIV = $xor; + } + } + + return $ciphertext; + } + + /** + * Decrypts a message. + * + * @access public + * @param String $ciphertext + */ + function decrypt($ciphertext) + { + if ($this->mode == CRYPT_DES_MODE_SSH && strlen($this->key) > 8) { + $plaintext = $this->des[0]->decrypt($this->des[1]->encrypt($this->des[2]->decrypt($ciphertext))); + + return $plaintext; + } + + // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic : + // "The data is padded with "\0" to make sure the length of the data is n * blocksize." + $ciphertext = str_pad($ciphertext, (strlen($ciphertext) + 7) & 0xFFFFFFF8, chr(0)); + + if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) { + $td = mcrypt_module_open(MCRYPT_3DES, $this->mcrypt[0], $this->mode, $this->mcrypt[1]); + mcrypt_generic_init($td, $this->key, $this->decryptIV); + + $plaintext = mdecrypt_generic($td, $ciphertext); + + mcrypt_generic_deinit($td); + mcrypt_module_close($td); + + if ($this->continuousBuffer) { + $this->decryptIV = substr($ciphertext, -8); + } + + return $this->_unpad($plaintext); + } + + if (strlen($this->key) <= 8) { + $this->des[0]->mode = $this->mode; + + return $this->des[0]->decrypt($plaintext); + } + + $plaintext = ''; + switch ($this->mode) { + case CRYPT_DES_MODE_ECB: + for ($i = 0; $i < strlen($ciphertext); $i+=8) { + $block = substr($ciphertext, $i, 8); + $block = $this->des[0]->_processBlock($block, CRYPT_DES_DECRYPT); + $block = $this->des[1]->_processBlock($block, CRYPT_DES_ENCRYPT); + $block = $this->des[2]->_processBlock($block, CRYPT_DES_DECRYPT); + $plaintext.= $block; + } + break; + case CRYPT_DES_MODE_CBC: + $xor = $this->decryptIV; + for ($i = 0; $i < strlen($ciphertext); $i+=8) { + $orig = $block = substr($ciphertext, $i, 8); + $block = $this->des[0]->_processBlock($block, CRYPT_DES_DECRYPT); + $block = $this->des[1]->_processBlock($block, CRYPT_DES_ENCRYPT); + $block = $this->des[2]->_processBlock($block, CRYPT_DES_DECRYPT); + $plaintext.= $block ^ $xor; + $xor = $orig; + } + if ($this->continuousBuffer) { + $this->decryptIV = $xor; + } + } + + return $this->_unpad($plaintext); + } + + /** + * Treat consecutive "packets" as if they are a continuous buffer. + * + * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets + * will yield different outputs: + * + * + * echo $des->encrypt(substr($plaintext, 0, 8)); + * echo $des->encrypt(substr($plaintext, 8, 8)); + * + * + * echo $des->encrypt($plaintext); + * + * + * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates + * another, as demonstrated with the following: + * + * + * $des->encrypt(substr($plaintext, 0, 8)); + * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8))); + * + * + * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8))); + * + * + * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different + * outputs. The reason is due to the fact that the initialization vector's change after every encryption / + * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant. + * + * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each + * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that + * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them), + * however, they are also less intuitive and more likely to cause you problems. + * + * @see Crypt_TripleDES::disableContinuousBuffer() + * @access public + */ + function enableContinuousBuffer() + { + $this->continuousBuffer = true; + } + + /** + * Treat consecutive packets as if they are a discontinuous buffer. + * + * The default behavior. + * + * @see Crypt_TripleDES::enableContinuousBuffer() + * @access public + */ + function disableContinuousBuffer() + { + $this->continuousBuffer = false; + $this->encryptIV = $this->iv; + $this->decryptIV = $this->iv; + } + + /** + * Pad "packets". + * + * DES works by encrypting eight bytes at a time. If you ever need to encrypt or decrypt something that's not + * a multiple of eight, it becomes necessary to pad the input so that it's length is a multiple of eight. + * + * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH1, + * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping + * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is + * transmitted separately) + * + * @see Crypt_TripleDES::disablePadding() + * @access public + */ + function enablePadding() + { + $this->padding = true; + } + + /** + * Do not pad packets. + * + * @see Crypt_TripleDES::enablePadding() + * @access public + */ + function disablePadding() + { + $this->padding = false; + } + + /** + * Pads a string + * + * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize (8). + * 8 - (strlen($text) & 7) bytes are added, each of which is equal to chr(8 - (strlen($text) & 7) + * + * @see Crypt_TripleDES::_unpad() + * @access private + */ + function _pad($text) + { + if (!$this->padding) { + return $text; + } + + $length = 8 - (strlen($text) & 7); + return str_pad($text, strlen($text) + $length, chr($length)); + } + + /** + * Unpads a string + * + * @see Crypt_TripleDES::_pad() + * @access private + */ + function _unpad($text) + { + if (!$this->padding) { + return $text; + } + + $length = ord($text{strlen($text) - 1}); + return substr($text, 0, -$length); + } +} + +// vim: ts=4:sw=4:et: +// vim6: fdl=1: +?> \ No newline at end of file diff --git a/phpseclib/Math/BigInteger.php b/phpseclib/Math/BigInteger.php new file mode 100644 index 00000000..bc06714e --- /dev/null +++ b/phpseclib/Math/BigInteger.php @@ -0,0 +1,2174 @@ +> and << cannot be used, nor can the modulo operator %, + * which only supports integers. Although this fact will slow this library down, the fact that such a high + * base is being used should more than compensate. + * + * When PHP version 6 is officially released, we'll be able to use 64-bit integers. This should, once again, + * allow bitwise operators, and will increase the maximum possible base to 2**31 (or 2**62 for addition / + * subtraction). + * + * Useful resources are as follows: + * + * - {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf Handbook of Applied Cryptography (HAC)} + * - {@link http://math.libtomcrypt.com/files/tommath.pdf Multi-Precision Math (MPM)} + * - Java's BigInteger classes. See /j2se/src/share/classes/java/math in jdk-1_5_0-src-jrl.zip + * + * One idea for optimization is to use the comba method to reduce the number of operations performed. + * MPM uses this quite extensively. The following URL elaborates: + * + * {@link http://www.everything2.com/index.pl?node_id=1736418}}} + * + * Here's a quick 'n dirty example of how to use this library: + * + * add($b); + * + * echo $c->toString(); // outputs 5 + * ?> + * + * + * LICENSE: This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + * + * @category Math + * @package Math_BigInteger + * @author Jim Wigginton + * @copyright MMVI Jim Wigginton + * @license http://www.gnu.org/licenses/lgpl.txt + * @version $Id: BigInteger.php,v 1.1 2007-07-02 04:19:47 terrafrost Exp $ + * @link http://pear.php.net/package/Math_BigInteger + */ + +/** + * Include PHP_Compat module bcpowmod since that function does not exist in PHP4: + * {@link http://pear.php.net/package/PHP_Compat/} + * {@link http://php.net/function.bcpowmod} + */ +require_once 'PHP/Compat/Function/bcpowmod.php'; +/** + * Include PHP_Compat module array_fill since that function requires PHP4.2.0+: + * {@link http://pear.php.net/package/PHP_Compat/} + * {@link http://php.net/function.array_fill} + */ +require_once 'PHP/Compat/Function/array_fill.php'; + +/**#@+ + * @access private + * @see Math_BigInteger::_slidingWindow() + */ +/** + * @see Math_BigInteger::_montgomery() + * @see Math_BigInteger::_undoMontgomery() + */ +define('MATH_BIGINTEGER_MONTGOMERY', 0); +/** + * @see Math_BigInteger::_barrett() + */ +define('MATH_BIGINTEGER_BARRETT', 1); +/** + * @see Math_BigInteger::_mod2() + */ +define('MATH_BIGINTEGER_POWEROF2', 2); +/** + * @see Math_BigInteger::_remainder() + */ +define('MATH_BIGINTEGER_CLASSIC', 3); +/** + * @see Math_BigInteger::_copy() + */ +define('MATH_BIGINTEGER_NONE', 4); +/**#@-*/ + +/**#@+ + * @access private + * @see Math_BigInteger::_montgomery() + * @see Math_BigInteger::_barrett() + */ +/** + * $cache[MATH_BIGINTEGER_VARIABLE] tells us whether or not the cached data is still valid. + */ +define('MATH_BIGINTEGER_VARIABLE', 0); +/** + * $cache[MATH_BIGINTEGER_DATA] contains the cached data. + */ +define('MATH_BIGINTEGER_DATA', 1); +/**#@-*/ + +/**#@+ + * @access private + * @see Math_BigInteger::Math_BigInteger() + */ +/** + * To use the pure-PHP implementation + */ +define('MATH_BIGINTEGER_MODE_INTERNAL', 1); +/** + * To use the BCMath library + * + * (if enabled; otherwise, the internal implementation will be used) + */ +define('MATH_BIGINTEGER_MODE_BCMATH', 2); +/** + * To use the GMP library + * + * (if present; otherwise, either the BCMath or the internal implementation will be used) + */ +define('MATH_BIGINTEGER_MODE_GMP', 3); +/**#@-*/ + +/** + * Pure-PHP arbitrary precission integer arithmetic library. Supports base-2, base-10, base-16, and base-256 + * numbers. + * + * @author Jim Wigginton + * @version 1.0.0RC3 + * @access public + * @package Math_BigInteger + */ +class Math_BigInteger { + /** + * Holds the BigInteger's value. + * + * @var Array + * @access private + */ + var $value; + + /** + * Holds the BigInteger's magnitude. + * + * @var Boolean + * @access private + */ + var $is_negative = false; + + /** + * Converts base-2, base-10, base-16, and binary strings (eg. base-256) to BigIntegers. + * + * If the second parameter - $base - is negative, then it will be assumed that the number's are encoded using + * two's compliment. The sole exception to this is -10, which is treated the same as 10 is. + * + * Here's a quick 'n dirty example: + * + * toString(); // outputs 50 + * ?> + * + * + * @param optional $x base-10 number or base-$base number if $base set. + * @param optional integer $base + * @return Math_BigInteger + * @access public + */ + function Math_BigInteger($x = 0, $base = 10) + { + if ( !defined('MATH_BIGINTEGER_MODE') ) { + switch (true) { + case extension_loaded('gmp'): + define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_GMP); + break; + case extension_loaded('bcmath'): + define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_BCMATH); + break; + default: + define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_INTERNAL); + } + } + + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + $this->value = gmp_init(0); + break; + case MATH_BIGINTEGER_MODE_BCMATH: + $this->value = '0'; + break; + default: + $this->value = array(); + } + + if ($x === 0) { + return; + } + + switch ($base) { + case -256: + if (ord($x[0]) & 0x80) { + $x = ~$x; + $this->is_negative = true; + } + case 256: + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = unpack('H*hex', $x); + $sign = $this->is_negative ? '-' : ''; + $this->value = gmp_init($sign . '0x' . $temp['hex']); + break; + case MATH_BIGINTEGER_MODE_BCMATH: + // round $len to the nearest 4 (thanks, DavidMJ!) + $len = (strlen($x) + 3) & 0xFFFFFFFC; + + $x = str_pad($x, $len, chr(0), STR_PAD_LEFT); + + for ($i = 0; $i < $len; $i+= 4) { + $this->value = bcmul($this->value, '4294967296'); // 4294967296 == 2**32 + $this->value = bcadd($this->value, 0x1000000 * ord($x[$i]) + ((ord($x[$i + 1]) << 16) | (ord($x[$i + 2]) << 8) | ord($x[$i + 3]))); + } + + if ($this->is_negative) { + $this->value = '-' . $this->value; + } + + break; + // converts a base-2**8 (big endian / msb) number to base-2**26 (little endian / lsb) + case MATH_BIGINTEGER_MODE_INTERNAL: + while (strlen($x)) { + $this->value[] = $this->_bytes2int($this->_base256_rshift($x, 26)); + } + } + + if ($this->is_negative) { + if (MATH_BIGINTEGER_MODE != MATH_BIGINTEGER_MODE_INTERNAL) { + $this->is_negative = false; + } + $temp = $this->add(new Math_BigInteger('-1')); + $this->value = $temp->value; + } + break; + case 16: + case -16: + if ($base > 0 && $x[0] == '-') { + $this->is_negative = true; + $x = substr($x, 1); + } + + $x = preg_replace('#^(?:0x)?([A-Fa-f0-9]*).*#', '$1', $x); + + $is_negative = false; + if ($base < 0 && hexdec($x[0]) >= 8) { + $this->is_negative = $is_negative = true; + $x = bin2hex(~pack('H*', $x)); + } + + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = $this->is_negative ? '-0x' . $x : '0x' . $x; + $this->value = gmp_init($temp); + $this->is_negative = false; + break; + case MATH_BIGINTEGER_MODE_BCMATH: + $x = ( strlen($x) & 1 ) ? '0' . $x : $x; + $temp = new Math_BigInteger(pack('H*', $x), 256); + $this->value = $this->is_negative ? '-' . $temp->value : $temp->value; + $this->is_negative = false; + break; + case MATH_BIGINTEGER_MODE_INTERNAL: + $x = ( strlen($x) & 1 ) ? '0' . $x : $x; + $temp = new Math_BigInteger(pack('H*', $x), 256); + $this->value = $temp->value; + } + + if ($is_negative) { + $temp = $this->add(new Math_BigInteger('-1')); + $this->value = $temp->value; + } + break; + case 10: + case -10: + $x = preg_replace('#^(-?[0-9]*).*#', '$1', $x); + + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + $this->value = gmp_init($x); + break; + case MATH_BIGINTEGER_MODE_BCMATH: + // explicitly casting $x to a string is necessary, here, since doing $x[0] on -1 yields different + // results then doing it on '-1' does (modInverse does $x[0]) + $this->value = (string) $x; + break; + case MATH_BIGINTEGER_MODE_INTERNAL: + $temp = new Math_BigInteger(); + + // array(10000000) is 10**7 in base-2**26. 10**7 is the closest to 2**26 we can get without passing it. + $multiplier = new Math_BigInteger(); + $multiplier->value = array(10000000); + + if ($x[0] == '-') { + $this->is_negative = true; + $x = substr($x, 1); + } + + $x = str_pad($x, strlen($x) + (6 * strlen($x)) % 7, 0, STR_PAD_LEFT); + + while (strlen($x)) { + $temp = $temp->multiply($multiplier); + $temp = $temp->add(new Math_BigInteger($this->_int2bytes(substr($x, 0, 7)), 256)); + $x = substr($x, 7); + } + + $this->value = $temp->value; + } + break; + case 2: // base-2 support originally implemented by Lluis Pamies - thanks! + case -2: + if ($base > 0 && $x[0] == '-') { + $this->is_negative = true; + $x = substr($x, 1); + } + + $x = preg_replace('#^([01]*).*#', '$1', $x); + $x = str_pad($x, strlen($x) + (3 * strlen($x)) % 4, 0, STR_PAD_LEFT); + + $str = '0x'; + while (strlen($x)) { + $part = substr($x, 0, 4); + $str.= dechex(bindec($part)); + $x = substr($x, 4); + } + + if ($this->is_negative) { + $str = '-' . $str; + } + + $temp = new Math_BigInteger($str, 8 * $base); // ie. either -16 or +16 + $this->value = $temp->value; + $this->is_negative = $temp->is_negative; + + break; + default: + // base not supported, so we'll let $this == 0 + } + } + + /** + * Converts a BigInteger to a byte string (eg. base-256). + * + * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're + * saved as two's compliment. + * + * Here's a quick 'n dirty example: + * + * toBytes(); // outputs chr(65) + * ?> + * + * + * @param Boolean $twos_compliment + * @return String + * @access public + * @internal Converts a base-2**26 number to base-2**8 + */ + function toBytes($twos_compliment = false) + { + if ($twos_compliment) { + $comparison = $this->compare(new Math_BigInteger()); + if ($comparison == 0) { + return ''; + } + + $temp = $comparison < 0 ? $this->add(new Math_BigInteger(1)) : $this->_copy(); + $bytes = $temp->toBytes(); + + if (empty($bytes)) { // eg. if the number we're trying to convert is -1 + $bytes = chr(0); + } + + if (ord($bytes[0]) & 0x80) { + $bytes = chr(0) . $bytes; + } + + return $comparison < 0 ? ~$bytes : $bytes; + } + + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + if (gmp_cmp($this->value, gmp_init(0)) == 0) { + return ''; + } + + $temp = gmp_strval(gmp_abs($this->value), 16); + $temp = ( strlen($temp) & 1 ) ? '0' . $temp : $temp; + + return ltrim(pack('H*', $temp), chr(0)); + case MATH_BIGINTEGER_MODE_BCMATH: + if ($this->value === '0') { + return ''; + } + + $value = ''; + $current = $this->value; + + if ($current[0] == '-') { + $current = substr($current, 1); + } + + // we don't do four bytes at a time because then numbers larger than 1<<31 would be negative + // two's complimented numbers, which would break chr. + while (bccomp($current, '0') > 0) { + $temp = bcmod($current, 0x1000000); + $value = chr($temp >> 16) . chr($temp >> 8) . chr($temp) . $value; + $current = bcdiv($current, 0x1000000); + } + + return ltrim($value, chr(0)); + } + + if (!count($this->value)) { + return ''; + } + + $result = $this->_int2bytes($this->value[count($this->value) - 1]); + + $temp = $this->_copy(); + + for ($i = count($temp->value) - 2; $i >= 0; $i--) { + $temp->_base256_lshift($result, 26); + $result = $result | str_pad($temp->_int2bytes($temp->value[$i]), strlen($result), chr(0), STR_PAD_LEFT); + } + + return $result; + } + + /** + * Converts a BigInteger to a base-10 number. + * + * Here's a quick 'n dirty example: + * + * toString(); // outputs 50 + * ?> + * + * + * @return String + * @access public + * @internal Converts a base-2**26 number to base-10**7 (which is pretty much base-10) + */ + function toString() + { + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + return gmp_strval($this->value); + case MATH_BIGINTEGER_MODE_BCMATH: + if ($this->value === '0') { + return '0'; + } + + return ltrim($this->value, '0'); + } + + if (!count($this->value)) { + return '0'; + } + + $temp = $this->_copy(); + $temp->is_negative = false; + + $divisor = new Math_BigInteger(); + $divisor->value = array(10000000); // eg. 10**7 + while (count($temp->value)) { + list($temp, $mod) = $temp->divide($divisor); + $result = str_pad($this->_bytes2int($mod->toBytes()), 7, '0', STR_PAD_LEFT) . $result; + } + $result = ltrim($result, '0'); + + if ($this->is_negative) { + $result = '-' . $result; + } + + return $result; + } + + /** + * Adds two BigIntegers. + * + * Here's a quick 'n dirty example: + * + * add($b); + * + * echo $c->toString(); // outputs 30 + * ?> + * + * + * @param Math_BigInteger $y + * @return Math_BigInteger + * @access public + * @internal Performs base-2**52 addition + */ + function add($y) + { + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = new Math_BigInteger(); + $temp->value = gmp_add($this->value, $y->value); + + return $temp; + case MATH_BIGINTEGER_MODE_BCMATH: + $temp = new Math_BigInteger(); + $temp->value = bcadd($this->value, $y->value); + + return $temp; + } + + // subtract, if appropriate + if ( $this->is_negative != $y->is_negative ) { + // is $y the negative number? + $y_negative = $this->compare($y) > 0; + + $temp = $this->_copy(); + $y = $y->_copy(); + $temp->is_negative = $y->is_negative = false; + + $diff = $temp->compare($y); + if ( !$diff ) { + return new Math_BigInteger(); + } + + $temp = $temp->subtract($y); + + $temp->is_negative = ($diff > 0) ? !$y_negative : $y_negative; + + return $temp; + } + + $result = new Math_BigInteger(); + $carry = 0; + + $size = max(count($this->value), count($y->value)); + $size+= $size & 1; // rounds $size to the nearest 2. + + $x = array_pad($this->value, $size,0); + $y = array_pad($y->value, $size, 0); + + for ($i = 0; $i < $size - 1; $i+=2) { + $sum = $x[$i + 1] * 0x4000000 + $x[$i] + $y[$i + 1] * 0x4000000 + $y[$i] + $carry; + $carry = $sum >= 4503599627370496; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1 + $sum = $carry ? $sum - 4503599627370496 : $sum; + + $temp = floor($sum / 0x4000000); + + $result->value[] = $sum - 0x4000000 * $temp; // eg. a faster alternative to fmod($sum, 0x4000000) + $result->value[] = $temp; + } + + if ($carry) { + $result->value[] = $carry; + } + + $result->is_negative = $this->is_negative; + + return $result->_normalize(); + } + + /** + * Subtracts two BigIntegers. + * + * Here's a quick 'n dirty example: + * + * subtract($b); + * + * echo $c->toString(); // outputs -10 + * ?> + * + * + * @param Math_BigInteger $y + * @return Math_BigInteger + * @access public + * @internal Performs base-2**52 subtraction + */ + function subtract($y) + { + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = new Math_BigInteger(); + $temp->value = gmp_sub($this->value, $y->value); + + return $temp; + case MATH_BIGINTEGER_MODE_BCMATH: + $temp = new Math_BigInteger(); + $temp->value = bcsub($this->value, $y->value); + + return $temp; + } + + // add, if appropriate + if ( $this->is_negative != $y->is_negative ) { + $is_negative = $y->compare($this) > 0; + + $temp = $this->_copy(); + $y = $y->_copy(); + $temp->is_negative = $y->is_negative = false; + + $temp = $temp->add($y); + + $temp->is_negative = $is_negative; + + return $temp; + } + + $diff = $this->compare($y); + + if ( !$diff ) { + return new Math_BigInteger(); + } + + // switch $this and $y around, if appropriate. + if ( (!$this->is_negative && $diff < 0) || ($this->is_negative && $diff > 0) ) { + $is_negative = $y->is_negative; + + $temp = $this->_copy(); + $y = $y->_copy(); + $temp->is_negative = $y->is_negative = false; + + $temp = $y->subtract($temp); + $temp->is_negative = !$is_negative; + + return $temp; + } + + $result = new Math_BigInteger(); + $carry = 0; + + $size = max(count($this->value), count($y->value)); + $size+= $size % 2; + + $x = array_pad($this->value, $size, 0); + $y = array_pad($y->value, $size, 0); + + for ($i = 0; $i < $size - 1;$i+=2) { + $sum = $x[$i + 1] * 0x4000000 + $x[$i] - $y[$i + 1] * 0x4000000 - $y[$i] + $carry; + $carry = $sum < 0 ? -1 : 0; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1 + $sum = $carry ? $sum + 4503599627370496 : $sum; + + $temp = floor($sum / 0x4000000); + + $result->value[] = $sum - 0x4000000 * $temp; + $result->value[] = $temp; + } + + // $carry shouldn't be anything other than zero, at this point, since we already made sure that $this + // was bigger than $y. + + $result->is_negative = $this->is_negative; + + return $result->_normalize(); + } + + /** + * Multiplies two BigIntegers + * + * Here's a quick 'n dirty example: + * + * multiply($b); + * + * echo $c->toString(); // outputs 200 + * ?> + * + * + * @param Math_BigInteger $x + * @return Math_BigInteger + * @access public + * @internal Modeled after 'multiply' in MutableBigInteger.java. + */ + function multiply($x) + { + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = new Math_BigInteger(); + $temp->value = gmp_mul($this->value, $x->value); + + return $temp; + case MATH_BIGINTEGER_MODE_BCMATH: + $temp = new Math_BigInteger(); + $temp->value = bcmul($this->value, $x->value); + + return $temp; + } + + if ( !$this->compare($x) ) { + return $this->_square(); + } + + $this_length = count($this->value); + $x_length = count($x->value); + + if ( !$this_length || !$x_length ) { // a 0 is being multiplied + return new Math_BigInteger(); + } + + $product = new Math_BigInteger(); + $product->value = $this->_array_repeat(0, $this_length + $x_length); + + // the following for loop could be removed if the for loop following it + // (the one with nested for loops) initially set $i to 0, but + // doing so would also make the result in one set of unnecessary adds, + // since on the outermost loops first pass, $product->value[$k] is going + // to always be 0 + + $carry = 0; + $i = 0; + + for ($j = 0, $k = $i; $j < $this_length; $j++, $k++) { + $temp = $product->value[$k] + $this->value[$j] * $x->value[$i] + $carry; + $carry = floor($temp / 0x4000000); + $product->value[$k] = $temp - 0x4000000 * $carry; + } + + $product->value[$k] = $carry; + + + // the above for loop is what the previous comment was talking about. the + // following for loop is the "one with nested for loops" + + for ($i = 1; $i < $x_length; $i++) { + $carry = 0; + + for ($j = 0, $k = $i; $j < $this_length; $j++, $k++) { + $temp = $product->value[$k] + $this->value[$j] * $x->value[$i] + $carry; + $carry = floor($temp / 0x4000000); + $product->value[$k] = $temp - 0x4000000 * $carry; + } + + $product->value[$k] = $carry; + } + + $product->is_negative = $this->is_negative != $x->is_negative; + + return $product->_normalize(); + } + + /** + * Squares a BigInteger + * + * Squaring can be done faster than multiplying a number by itself can be. See + * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=7 HAC 14.2.4} / + * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=141 MPM 5.3} for more information. + * + * @return Math_BigInteger + * @access private + */ + function _square() + { + if ( empty($this->value) ) { + return new Math_BigInteger(); + } + + $max_index = count($this->value) - 1; + + $square = new Math_BigInteger(); + $square->value = $this->_array_repeat(0, 2 * $max_index); + + for ($i = 0; $i <= $max_index; $i++) { + $temp = $square->value[2 * $i] + $this->value[$i] * $this->value[$i]; + $carry = floor($temp / 0x4000000); + $square->value[2 * $i] = $temp - 0x4000000 * $carry; + + // note how we start from $i+1 instead of 0 as we do in multiplication. + for ($j = $i + 1; $j <= $max_index; $j++) { + $temp = $square->value[$i + $j] + 2 * $this->value[$j] * $this->value[$i] + $carry; + $carry = floor($temp / 0x4000000); + $square->value[$i + $j] = $temp - 0x4000000 * $carry; + } + + // the following line can yield values larger 2**15. at this point, PHP should switch + // over to floats. + $square->value[$i + $max_index + 1] = $carry; + } + + return $square->_normalize(); + } + + /** + * Divides two BigIntegers. + * + * Returns an array whose first element contains the quotient and whose second element contains the + * "common residue". If the remainder would be positive, the "common residue" and the remainder are the + * same. If the remainder would be negative, the "common residue" is equal to the sum of the remainder + * and the divisor (basically, the "common residue" is the first positive modulo). + * + * Here's a quick 'n dirty example: + * + * divide($b); + * + * echo $quotient->toString(); // outputs 0 + * echo "\r\n"; + * echo $remainder->toString(); // outputs 10 + * ?> + * + * + * @param Math_BigInteger $y + * @return Array + * @access public + * @internal This function is based off of {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=9 HAC 14.20} + * with a slight variation due to the fact that this script, initially, did not support negative numbers. Now, + * it does, but I don't want to change that which already works. + */ + function divide($y) + { + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + $quotient = new Math_BigInteger(); + $remainder = new Math_BigInteger(); + + list($quotient->value, $remainder->value) = gmp_div_qr($this->value, $y->value); + + if (gmp_sign($remainder->value) < 0) { + $remainder->value = gmp_add($remainder->value, gmp_abs($y->value)); + } + + return array($quotient, $remainder); + case MATH_BIGINTEGER_MODE_BCMATH: + $quotient = new Math_BigInteger(); + $remainder = new Math_BigInteger(); + + $quotient->value = bcdiv($this->value, $y->value); + $remainder->value = bcmod($this->value, $y->value); + + if ($remainder->value[0] == '-') { + $remainder->value = bcadd($remainder->value, $y->value[0] == '-' ? substr($y->value, 1) : $y->value); + } + + return array($quotient, $remainder); + } + + $x = $this->_copy(); + $y = $y->_copy(); + + $x_sign = $x->is_negative; + $y_sign = $y->is_negative; + + $x->is_negative = $y->is_negative = false; + + $diff = $x->compare($y); + + if ( !$diff ) { + $temp = new Math_BigInteger(); + $temp->value = array(1); + $temp->is_negative = $x_sign != $y_sign; + return array($temp, new Math_BigInteger()); + } + + if ( $diff < 0 ) { + // if $x is negative, "add" $y. + if ( $x_sign ) { + $x = $y->subtract($x); + } + return array(new Math_BigInteger(), $x); + } + + // normalize $x and $y as described in HAC 14.23 / 14.24 + // (incidently, i haven't been able to find a definitive example showing that this + // results in worth-while speedup, but whatever) + $msb = $y->value[count($y->value) - 1]; + for ($shift = 0; !($msb & 0x2000000); $shift++) { + $msb <<= 1; + } + $x->_lshift($shift); + $y->_lshift($shift); + + $x_max = count($x->value) - 1; + $y_max = count($y->value) - 1; + + $quotient = new Math_BigInteger(); + $quotient->value = $this->_array_repeat(0, $x_max - $y_max + 1); + + // $temp = $y << ($x_max - $y_max-1) in base 2**26 + $temp = new Math_BigInteger(); + $temp->value = array_merge($this->_array_repeat(0, $x_max - $y_max), $y->value); + + while ( $x->compare($temp) >= 0 ) { + // calculate the "common residue" + $quotient->value[$x_max - $y_max]++; + $x = $x->subtract($temp); + $x_max = count($x->value) - 1; + } + + for ($i = $x_max; $i >= $y_max + 1; $i--) { + $x_value = array( + $x->value[$i], + ( $i > 0 ) ? $x->value[$i - 1] : 0, + ( $i - 1 > 0 ) ? $x->value[$i - 2] : 0 + ); + $y_value = array( + $y->value[$y_max], + ( $y_max > 0 ) ? $y_max - 1 : 0 + ); + + + $q_index = $i - $y_max - 1; + if ($x_value[0] == $y_value[0]) { + $quotient->value[$q_index] = 0x3FFFFFF; + } else { + $quotient->value[$q_index] = floor( + ($x_value[0] * 0x4000000 + $x_value[1]) + / + $y_value[0] + ); + } + + $temp = new Math_BigInteger(); + $temp->value = array($y_value[1], $y_value[0]); + + $lhs = new Math_BigInteger(); + $lhs->value = array($quotient->value[$q_index]); + $lhs = $lhs->multiply($temp); + + $rhs = new Math_BigInteger(); + $rhs->value = array($x_value[2], $x_value[1], $x_value[0]); + + while ( $lhs->compare($rhs) > 0 ) { + $quotient->value[$q_index]--; + + $lhs = new Math_BigInteger(); + $lhs->value = array($quotient->value[$q_index]); + $lhs = $lhs->multiply($temp); + } + + $corrector = new Math_BigInteger(); + $temp = new Math_BigInteger(); + $corrector->value = $temp->value = $this->_array_repeat(0, $q_index); + $temp->value[] = $quotient->value[$q_index]; + + $temp = $temp->multiply($y); + + if ( $x->compare($temp) < 0 ) { + $corrector->value[] = 1; + $x = $x->add($corrector->multiply($y)); + $quotient->value[$q_index]--; + } + + $x = $x->subtract($temp); + $x_max = count($x->value) - 1; + } + + // unnormalize the remainder + $x->_rshift($shift); + + $quotient->is_negative = $x_sign != $y_sign; + + // calculate the "common residue", if appropriate + if ( $x_sign ) { + $y->_rshift($shift); + $x = $y->subtract($x); + } + + return array($quotient->_normalize(), $x); + } + + /** + * Performs modular exponentiation. + * + * Here's a quick 'n dirty example: + * + * modPow($b, $c); + * + * echo $c->toString(); // outputs 10 + * ?> + * + * + * @param Math_BigInteger $e + * @param Math_BigInteger $n + * @return Math_BigInteger + * @access public + * @internal The most naive approach to modular exponentiation has very unreasonable requirements, and + * and although the approach involving repeated squaring does vastly better, it, too, is impractical + * for our purposes. The reason being that division - by far the most complicated and time-consuming + * of the basic operations (eg. +,-,*,/) - occurs multiple times within it. + * + * Modular reductions resolve this issue. Although an individual modular reduction takes more time + * then an individual division, when performed in succession (with the same modulo), they're a lot faster. + * + * The two most commonly used modular reductions are Barrett and Montgomery reduction. Montgomery reduction, + * although faster, only works when the gcd of the modulo and of the base being used is 1. In RSA, when the + * base is a power of two, the modulo - a product of two primes - is always going to have a gcd of 1 (because + * the product of two odd numbers is odd), but what about when RSA isn't used? + * + * In contrast, Barrett reduction has no such constraint. As such, some bigint implementations perform a + * Barrett reduction after every operation in the modpow function. Others perform Barrett reductions when the + * modulo is even and Montgomery reductions when the modulo is odd. BigInteger.java's modPow method, however, + * uses a trick involving the Chinese Remainder Theorem to factor the even modulo into two numbers - one odd and + * the other, a power of two - and recombine them, later. This is the method that this modPow function uses. + * {@link http://islab.oregonstate.edu/papers/j34monex.pdf Montgomery Reduction with Even Modulus} elaborates. + */ + function modPow($e, $n) + { + $n = $n->abs(); + if ($e->compare(new Math_BigInteger()) < 0) { + $e = $e->abs(); + + $temp = $this->modInverse($n); + if ($temp === false) { + return false; + } + + return $temp->modPow($e,$n); + } + + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = new Math_BigInteger(); + $temp->value = gmp_powm($this->value, $e->value, $n->value); + + return $temp; + case MATH_BIGINTEGER_MODE_BCMATH: + $temp = new Math_BigInteger(); + $temp->value = bcpowmod($this->value, $e->value, $n->value); + + return $temp; + } + + if ( empty($e->value) ) { + $temp = new Math_BigInteger(); + $temp->value = array(1); + return $temp; + } + + if ( $e->value == array(1) ) { + list(, $temp) = $this->divide($n); + return $temp; + } + + if ( $e->value == array(2) ) { + $temp = $this->_square(); + list(, $temp) = $temp->divide($n); + return $temp; + } + + // is the modulo odd? + if ( $n->value[0] & 1 ) { + return $this->_slidingWindow($e, $n, MATH_BIGINTEGER_MONTGOMERY); + } + // if it's not, it's even + + // find the lowest set bit (eg. the max pow of 2 that divides $n) + for ($i = 0; $i < count($n->value); $i++) { + if ( $n->value[$i] ) { + $temp = decbin($n->value[$i]); + $j = strlen($temp) - strrpos($temp, '1') - 1; + $j+= 26 * $i; + break; + } + } + // at this point, 2^$j * $n/(2^$j) == $n + + $mod1 = $n->_copy(); + $mod1->_rshift($j); + $mod2 = new Math_BigInteger(); + $mod2->value = array(1); + $mod2->_lshift($j); + + $part1 = ( $mod1->value != array(1) ) ? $this->_slidingWindow($e, $mod1, MATH_BIGINTEGER_MONTGOMERY) : new Math_BigInteger(); + $part2 = $this->_slidingWindow($e, $mod2, MATH_BIGINTEGER_POWEROF2); + + $y1 = $mod2->modInverse($mod1); + $y2 = $mod1->modInverse($mod2); + + $result = $part1->multiply($mod2); + $result = $result->multiply($y1); + + $temp = $part2->multiply($mod1); + $temp = $temp->multiply($y2); + + $result = $result->add($temp); + list(, $result) = $result->divide($n); + + return $result; + } + + /** + * Sliding Window k-ary Modular Exponentiation + * + * Based on {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=27 HAC 14.85} / + * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=210 MPM 7.7}. In a departure from those algorithims, + * however, this function performs a modular reduction after every multiplication and squaring operation. + * As such, this function has the same preconditions that the reductions being used do. + * + * The window size is calculated in the same fashion that the window size in BigInteger.java's oddModPow + * function is. + * + * @param Math_BigInteger $e + * @param Math_BigInteger $n + * @param Integer $mode + * @return Math_BigInteger + * @access private + */ + function _slidingWindow($e, $n, $mode) + { + static $window_ranges = array(7, 25, 81, 241, 673, 1793); + + $e_length = count($e->value) - 1; + $e_bits = decbin($e->value[$e_length]); + for ($i = $e_length - 1; $i >= 0; $i--) { + $e_bits.= str_pad(decbin($e->value[$i]), 26, '0', STR_PAD_LEFT); + } + $e_length = strlen($e_bits); + + // calculate the appropriate window size. + // $window_size == 3 if $window_ranges is between 25 and 81, for example. + for ($i = 0, $window_size = 1; $e_length > $window_ranges[$i] && $i < count($window_ranges); $window_size++, $i++); + + switch ($mode) { + case MATH_BIGINTEGER_MONTGOMERY: + $reduce = '_montgomery'; + $undo = '_undoMontgomery'; + break; + case MATH_BIGINTEGER_BARRETT: + $reduce = '_barrett'; + $undo = '_barrett'; + break; + case MATH_BIGINTEGER_POWEROF2: + $reduce = '_mod2'; + $undo = '_mod2'; + break; + case MATH_BIGINTEGER_CLASSIC: + $reduce = '_remainder'; + $undo = '_remainder'; + break; + case MATH_BIGINTEGER_NONE: + // ie. do no modular reduction. useful if you want to just do pow as opposed to modPow. + $reduce = '_copy'; + $undo = '_copy'; + break; + default: + // an invalid $mode was provided + } + + // precompute $this^0 through $this^$window_size + $powers = array(); + $powers[1] = $this->$undo($n); + $powers[2] = $powers[1]->_square(); + $powers[2] = $powers[2]->$reduce($n); + + // we do every other number since substr($e_bits, $i, $j+1) (see below) is supposed to end + // in a 1. ie. it's supposed to be odd. + $temp = 1 << ($window_size - 1); + for ($i = 1; $i < $temp; $i++) { + $powers[2 * $i + 1] = $powers[2 * $i - 1]->multiply($powers[2]); + $powers[2 * $i + 1] = $powers[2 * $i + 1]->$reduce($n); + } + + $result = new Math_BigInteger(); + $result->value = array(1); + $result = $result->$undo($n); + + for ($i = 0; $i < $e_length; ) { + if ( !$e_bits{$i} ) { + $result = $result->_square(); + $result = $result->$reduce($n); + $i++; + } else { + for ($j = $window_size - 1; $j >= 0; $j--) { + if ( $e_bits{$i + $j} ) { + break; + } + } + + for ($k = 0; $k <= $j; $k++) {// eg. the length of substr($e_bits, $i, $j+1) + $result = $result->_square(); + $result = $result->$reduce($n); + } + + $result = $result->multiply($powers[bindec(substr($e_bits, $i, $j + 1))]); + $result = $result->$reduce($n); + + $i+=$j + 1; + } + } + + $result = $result->$reduce($n); + return $result->_normalize(); + } + + /** + * Remainder + * + * A wrapper for the divide function. + * + * @see divide() + * @see _slidingWindow() + * @access private + * @param Math_BigInteger + * @return Math_BigInteger + */ + function _remainder($n) + { + list(, $temp) = $this->divide($n); + return $temp; + } + + /** + * Modulos for Powers of Two + * + * Calculates $x%$n, where $n = 2**$e, for some $e. Since this is basically the same as doing $x & ($n-1), + * we'll just use this function as a wrapper for doing that. + * + * @see _slidingWindow() + * @access private + * @param Math_BigInteger + * @return Math_BigInteger + */ + function _mod2($n) + { + $temp = new Math_BigInteger(); + $temp->value = array(1); + return $this->bitwise_and($n->subtract($temp)); + } + + /** + * Barrett Modular Reduction + * + * See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=14 HAC 14.3.3} / + * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=165 MPM 6.2.5} for more information. Modified slightly, + * so as not to require negative numbers (initially, this script didn't support negative numbers). + * + * @see _slidingWindow() + * @access private + * @param Math_BigInteger + * @return Math_BigInteger + */ + function _barrett($n) + { + static $cache; + + $n_length = count($n->value); + + if ( !isset($cache[MATH_BIGINTEGER_VARIABLE]) || $n->compare($cache[MATH_BIGINTEGER_VARIABLE]) ) { + $cache[MATH_BIGINTEGER_VARIABLE] = $n; + $temp = new Math_BigInteger(); + $temp->value = $this->_array_repeat(0, 2 * $n_length); + $temp->value[] = 1; + list($cache[MATH_BIGINTEGER_DATA], ) = $temp->divide($n); + } + + $temp = new Math_BigInteger(); + $temp->value = array_slice($this->value, $n_length - 1); + $temp = $temp->multiply($cache[MATH_BIGINTEGER_DATA]); + $temp->value = array_slice($temp->value, $n_length + 1); + + $result = new Math_BigInteger(); + $result->value = array_slice($this->value, 0, $n_length + 1); + $temp = $temp->multiply($n); + $temp->value = array_slice($temp->value, 0, $n_length + 1); + + if ($result->compare($temp) < 0) { + $corrector = new Math_BigInteger(); + $corrector->value = $this->_array_repeat(0, $n_length + 1); + $corrector->value[] = 1; + $result = $result->add($corrector); + } + + $result = $result->subtract($temp); + while ($result->compare($n) > 0) { + $result = $result->subtract($n); + } + + return $result; + } + + /** + * Montgomery Modular Reduction + * + * ($this->_montgomery($n))->_undoMontgomery($n) yields $x%$n. + * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=170 MPM 6.3} provides insights on how this can be + * improved upon (basically, by using the comba method). gcd($n, 2) must be equal to one for this function + * to work correctly. + * + * @see _undoMontgomery() + * @see _slidingWindow() + * @access private + * @param Math_BigInteger + * @return Math_BigInteger + */ + function _montgomery($n) + { + static $cache; + + if ( !isset($cache[MATH_BIGINTEGER_VARIABLE]) || $n->compare($cache[MATH_BIGINTEGER_VARIABLE]) ) { + $cache[MATH_BIGINTEGER_VARIABLE] = $n; + $cache[MATH_BIGINTEGER_DATA] = $n->_modInverse67108864(); + } + + $result = $this->_copy(); + + $n_length = count($n->value); + + for ($i = 0; $i < $n_length; $i++) { + $temp = new Math_BigInteger(); + $temp->value = array( + ($result->value[$i] * $cache[MATH_BIGINTEGER_DATA]) & 0x3FFFFFF + ); + $temp = $temp->multiply($n); + $temp->value = array_merge($this->_array_repeat(0, $i), $temp->value); + $result = $result->add($temp); + } + + $result->value = array_slice($result->value, $n_length); + + if ($result->compare($n) >= 0) { + $result = $result->subtract($n); + } + + return $result->_normalize(); + } + + /** + * Undo Montgomery Modular Reduction + * + * @see _montgomery() + * @see _slidingWindow() + * @access private + * @param Math_BigInteger + * @return Math_BigInteger + */ + function _undoMontgomery($n) + { + $temp = new Math_BigInteger(); + $temp->value = array_merge($this->_array_repeat(0, count($n->value)), $this->value); + list(, $temp) = $temp->divide($n); + return $temp->_normalize(); + } + + /** + * Modular Inverse of a number mod 2**26 (eg. 67108864) + * + * Based off of the bnpInvDigit function implemented and justified in the following URL: + * + * {@link http://www-cs-students.stanford.edu/~tjw/jsbn/jsbn.js} + * + * The following URL provides more info: + * + * {@link http://groups.google.com/group/sci.crypt/msg/7a137205c1be7d85} + * + * As for why we do all the bitmasking... strange things can happen when converting from flots to ints. For + * instance, on some computers, var_dump((int) -4294967297) yields int(-1) and on others, it yields + * int(-2147483648). To avoid problems stemming from this, we use bitmasks to guarntee that ints aren't + * auto-converted to floats. The outermost bitmask is present because without it, there's no guarantee that + * the "residue" returned would be the so-called "common residue". We use fmod, in the last step, because the + * maximum possible $x is 26 bits and the maximum $result is 16 bits. Thus, we have to be able to handle up to + * 40 bits, which only 64-bit floating points will support. + * + * Thanks to Pedro Gimeno Fortea for input! + * + * @see _montgomery() + * @access private + * @return Integer + */ + function _modInverse67108864() // 2**26 == 67108864 + { + $x = -$this->value[0]; + $result = $x & 0x3; // x**-1 mod 2**2 + $result = ($result * (2 - $x * $result)) & 0xF; // x**-1 mod 2**4 + $result = ($result * (2 - ($x & 0xFF) * $result)) & 0xFF; // x**-1 mod 2**8 + $result = ($result * ((2 - ($x & 0xFFFF) * $result) & 0xFFFF)) & 0xFFFF; // x**-1 mod 2**16 + $result = fmod($result * (2 - fmod($x * $result, 0x4000000)), 0x4000000); // x**-1 mod 2**26 + return $result & 0x3FFFFFF; + } + + /** + * Calculates modular inverses. + * + * Here's a quick 'n dirty example: + * + * modInverse($b); + * + * echo $c->toString(); // outputs 4 + * ?> + * + * + * @param Math_BigInteger $n + * @return mixed false, if no modular inverse exists, Math_BigInteger, otherwise. + * @access public + * @internal Calculates the modular inverse of $this mod $n using the binary xGCD algorithim described in + * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=19 HAC 14.61}. As the text above 14.61 notes, + * the more traditional algorithim requires "relatively costly multiple-precision divisions". See + * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=21 HAC 14.64} for more information. + */ + function modInverse($n) + { + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = new Math_BigInteger(); + $temp->value = gmp_invert($this->value, $n->value); + + return ( $temp->value === false ) ? false : $temp; + case MATH_BIGINTEGER_MODE_BCMATH: + // it might be faster to use the binary xGCD algorithim here, as well, but (1) that algorithim works + // best when the base is a power of 2 and (2) i don't think it'd make much difference, anyway. as is, + // the basic extended euclidean algorithim is what we're using. + + // if $x is less than 0, the first character of $x is a '-', so we'll remove it. we can do this because + // $x mod $n == $x mod -$n. + $n = (bccomp($n->value, '0') < 0) ? substr($n->value, 1) : $n->value; + + if (bccomp($this->value,'0') < 0) { + $negated_this = new Math_BigInteger(); + $negated_this->value = substr($this->value, 1); + + $temp = $negated_this->modInverse(new Math_BigInteger($n)); + + if ($temp === false) { + return false; + } + + $temp->value = bcsub($n, $temp->value); + + return $temp; + } + + $u = $this->value; + $v = $n; + + $a = '1'; + $c = '0'; + + while (true) { + $q = bcdiv($u, $v); + $temp = $u; + $u = $v; + $v = bcsub($temp, bcmul($v, $q)); + + if (bccomp($v, '0') == 0) { + break; + } + + $temp = $a; + $a = $c; + $c = bcsub($temp, bcmul($c, $q)); + } + + $temp = new Math_BigInteger(); + $temp->value = (bccomp($c, '0') < 0) ? bcadd($c, $n) : $c; + + // $u contains the gcd of $this and $n + return (bccomp($u,'1') == 0) ? $temp : false; + } + + // if $this and $n are even, return false. + if ( !($this->value[0]&1) && !($n->value[0]&1) ) { + return false; + } + + $n = $n->_copy(); + $n->is_negative = false; + + if ($this->compare(new Math_BigInteger()) < 0) { + // is_negative is currently true. since we need it to be false, we'll just set it to false, temporarily, + // and reset it as true, later. + $this->is_negative = false; + + $temp = $this->modInverse($n); + + if ($temp === false) { + return false; + } + + $temp = $n->subtract($temp); + + $this->is_negative = true; + + return $temp; + } + + $u = $n->_copy(); + $x = $this; + //list(, $x) = $this->divide($n); + $v = $x->_copy(); + + $a = new Math_BigInteger(); + $b = new Math_BigInteger(); + $c = new Math_BigInteger(); + $d = new Math_BigInteger(); + + $a->value = $d->value = array(1); + + while ( !empty($u->value) ) { + while ( !($u->value[0] & 1) ) { + $u->_rshift(1); + if ( ($a->value[0] & 1) || ($b->value[0] & 1) ) { + $a = $a->add($x); + $b = $b->subtract($n); + } + $a->_rshift(1); + $b->_rshift(1); + } + + while ( !($v->value[0] & 1) ) { + $v->_rshift(1); + if ( ($c->value[0] & 1) || ($d->value[0] & 1) ) { + $c = $c->add($x); + $d = $d->subtract($n); + } + $c->_rshift(1); + $d->_rshift(1); + } + + if ($u->compare($v) >= 0) { + $u = $u->subtract($v); + $a = $a->subtract($c); + $b = $b->subtract($d); + } else { + $v = $v->subtract($u); + $c = $c->subtract($a); + $d = $d->subtract($b); + } + + $u->_normalize(); + } + + // at this point, $v == gcd($this, $n). if it's not equal to 1, no modular inverse exists. + if ( $v->value != array(1) ) { + return false; + } + + $d = ($d->compare(new Math_BigInteger()) < 0) ? $d->add($n) : $d; + + return ($this->is_negative) ? $n->subtract($d) : $d; + } + + /** + * Absolute value. + * + * @return Math_BigInteger + * @access public + */ + function abs() + { + $temp = new Math_BigInteger(); + + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + $temp->value = gmp_abs($this->value); + break; + case MATH_BIGINTEGER_MODE_BCMATH: + $temp->value = (bccomp($this->value, '0') < 0) ? substr($this->value, 1) : $this->value; + break; + default: + $temp->value = $this->value; + } + + return $temp; + } + + /** + * Compares two numbers. + * + * @param Math_BigInteger $x + * @return Integer < 0 if $this is less than $x; > 0 if $this is greater than $x, and 0 if they are equal. + * @access public + * @internal Could return $this->sub($x), but that's not as fast as what we do do. + */ + function compare($x) + { + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + return gmp_cmp($this->value, $x->value); + case MATH_BIGINTEGER_MODE_BCMATH: + return bccomp($this->value, $x->value); + } + + $this->_normalize(); + $x->_normalize(); + + if ( $this->is_negative != $x->is_negative ) { + return ( !$this->is_negative && $x->is_negative ) ? 1 : -1; + } + + $result = $this->is_negative ? -1 : 1; + + if ( count($this->value) != count($x->value) ) { + return ( count($this->value) > count($x->value) ) ? $result : -$result; + } + + for ($i = count($this->value) - 1; $i >= 0; $i--) { + if ($this->value[$i] != $x->value[$i]) { + return ( $this->value[$i] > $x->value[$i] ) ? $result : -$result; + } + } + + return 0; + } + + /** + * Returns a copy of $this + * + * PHP5 passes objects by reference while PHP4 passes by value. As such, we need a function to guarantee + * that all objects are passed by value, when appropriate. More information can be found here: + * + * {@link http://www.php.net/manual/en/language.oop5.basic.php#51624} + * + * @access private + * @return Math_BigInteger + */ + function _copy() + { + $temp = new Math_BigInteger(); + $temp->value = $this->value; + $temp->is_negative = $this->is_negative; + return $temp; + } + + /** + * Logical And + * + * @param Math_BigInteger $x + * @access public + * @internal Implemented per a request by Lluis Pamies i Juarez + * @return Math_BigInteger + */ + function bitwise_and($x) + { + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = new Math_BigInteger(); + $temp->value = gmp_and($this->value, $x->value); + + return $temp; + case MATH_BIGINTEGER_MODE_BCMATH: + return new Math_BigInteger($this->toBytes() & $x->toBytes(), 256); + } + + $result = new Math_BigInteger(); + + $x_length = count($x->value); + for ($i = 0; $i < $x_length; $i++) { + $result->value[] = $this->value[$i] & $x->value[$i]; + } + + return $result->_normalize(); + } + + /** + * Logical Or + * + * @param Math_BigInteger $x + * @access public + * @internal Implemented per a request by Lluis Pamies i Juarez + * @return Math_BigInteger + */ + function bitwise_or($x) + { + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = new Math_BigInteger(); + $temp->value = gmp_or($this->value, $x->value); + + return $temp; + case MATH_BIGINTEGER_MODE_BCMATH: + return new Math_BigInteger($this->toBytes() | $x->toBytes(), 256); + } + + $result = new Math_BigInteger(); + + $x_length = count($x->value); + for ($i = 0; $i < $x_length; $i++) { + $result->value[] = $this->value[$i] | $x->value[$i]; + } + + return $result->_normalize(); + } + + /** + * Logical Exclusive-Or + * + * @param Math_BigInteger $x + * @access public + * @internal Implemented per a request by Lluis Pamies i Juarez + * @return Math_BigInteger + */ + function bitwise_xor($x) + { + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = new Math_BigInteger(); + $temp->value = gmp_xor($this->value, $x->value); + + return $temp; + case MATH_BIGINTEGER_MODE_BCMATH: + return new Math_BigInteger($this->toBytes() ^ $x->toBytes(), 256); + } + + $result = new Math_BigInteger(); + + $x_length = count($x->value); + for ($i = 0; $i < $x_length; $i++) { + $result->value[] = $this->value[$i] ^ $x->value[$i]; + } + + return $result->_normalize(); + } + + /** + * Logical Not + * + * Although integers can be converted to and from various bases with relative ease, there is one piece + * of information that is lost during such conversions. The number of leading zeros that number had + * or should have in any given base. Per that, if you convert 1 from decimal to binary, there's no + * way to know just how many leading zero's there should be. In truth, there could be any number. + * + * Normally, the number of leading zero's is unimportant. When doing "not", however, it is. The "not" + * of 1 on an 8-bit representation of 1 is 1111 1110. The "not" of 1 on a 16-bit representation of 1 is + * 1111 1111 1111 1110. When doing it on a number that's preceeded by an infinite number of zero's, it's + * infinite. + * + * This function assumes that there are no leading zero's - that the bit-representation being used is + * equal to the minimum number of required bits, unless otherwise specified in the optional parameter, + * where the optional parameter represents the bit-representation being used. If the specified + * bit-representation is smaller than the minimum number of bits required to represent the number, the + * latter will be used as the bit-representation. + * + * @param $bits Integer + * @access public + * @internal Implemented per a request by Lluis Pamies i Juarez + * @return Math_BigInteger + */ + function bitwise_not($bits = -1) + { + // calculuate "not" without regard to $bits + $temp = ~$this->toBytes(); + $msb = decbin(ord($temp[0])); + $msb = substr($msb, strpos($msb, '0')); + $temp[0] = chr(bindec($msb)); + + // see if we need to add extra leading 1's + $current_bits = strlen($msb) + 8 * strlen($temp) - 8; + $new_bits = $bits - $current_bits; + if ($new_bits <= 0) { + return new Math_BigInteger($temp, 256); + } + + // generate as many leading 1's as we need to. + $leading_ones = chr((1 << ($new_bits & 0x7)) - 1) . str_repeat(chr(0xFF), $new_bits >> 3); + $this->_base256_lshift($leading_ones, $current_bits); + + $temp = str_pad($temp, ceil($bits / 8), chr(0), STR_PAD_LEFT); + + return new Math_BigInteger($leading_ones | $temp, 256); + } + + /** + * Logical Right Shift + * + * Shifts BigInteger's by $shift bits, effectively dividing by 2**$shift. + * + * @param Integer $shift + * @return Math_BigInteger + * @access public + * @internal The only version that yields any speed increases is the internal version. + */ + function bitwise_rightShift($shift) + { + $temp = new Math_BigInteger(); + + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + static $two; + + if (empty($two)) { + $two = gmp_init('2'); + } + + $temp->value = gmp_div_q($this->value, gmp_pow($two, $shift)); + + break; + case MATH_BIGINTEGER_MODE_BCMATH: + + $temp->value = bcdiv($this->value, bcpow('2', $shift)); + + break; + default: // could just replace _lshift with this, but then all _lshift() calls would need to be rewritten + // and I don't want to do that... + $temp->value = $this->value; + $temp->_rshift($shift); + } + + return $temp; + } + + /** + * Logical Left Shift + * + * Shifts BigInteger's by $shift bits, effectively multiplying by 2**$shift. + * + * @param Integer $shift + * @return Math_BigInteger + * @access public + * @internal The only version that yields any speed increases is the internal version. + */ + function bitwise_leftShift($shift) + { + $temp = new Math_BigInteger(); + + switch ( MATH_BIGINTEGER_MODE ) { + case MATH_BIGINTEGER_MODE_GMP: + static $two; + + if (empty($two)) { + $two = gmp_init('2'); + } + + $temp->value = gmp_mul($this->value, gmp_pow($two, $shift)); + + break; + case MATH_BIGINTEGER_MODE_BCMATH: + $temp->value = bcmul($this->value, bcpow('2', $shift)); + + break; + default: // could just replace _rshift with this, but then all _lshift() calls would need to be rewritten + // and I don't want to do that... + $temp->value = $this->value; + $temp->_lshift($shift); + } + + return $temp; + } + + /** + * Generate a random number + * + * $generator should be the name of a random number generating function whose first parameter is the minimum + * value and whose second parameter is the maximum value. If this function needs to be seeded, it should be + * done before this function is called. + * + * @param optional Integer $min + * @param optional Integer $max + * @param optional String $generator + * @return Math_BigInteger + * @access public + */ + function random($min = false, $max = false, $generator = 'mt_rand') + { + if ($min === false) { + $min = new Math_BigInteger(0); + } + + if ($max === false) { + $max = new Math_BigInteger(0x7FFFFFFF); + } + + $compare = $max->compare($min); + + if (!$compare) { + return $min; + } else if ($compare < 0) { + // if $min is bigger then $max, swap $min and $max + $temp = $max; + $max = $min; + $min = $temp; + } + + $max = $max->subtract($min); + $max = ltrim($max->toBytes(), chr(0)); + $size = strlen($max) - 1; + + $bytes = $size & 3; + for ($i = 0; $i < $bytes; $i++) { + $random.= chr($generator(0, 255)); + } + + $blocks = $size >> 2; + for ($i = 0; $i < $blocks; $i++) { + $random.= pack('N', $generator(-2147483648, 0x7FFFFFFF)); + } + + $temp = new Math_BigInteger($random, 256); + if ($temp->compare(new Math_BigInteger(substr($max, 1), 256)) > 0) { + $random = chr($generator(0, ord($max[0]) - 1)) . $random; + } else { + $random = chr($generator(0, ord($max[0]) )) . $random; + } + + $random = new Math_BigInteger($random, 256); + + return $random->add($min); + } + + /** + * Logical Left Shift + * + * Shifts BigInteger's by $shift bits. + * + * @param Integer $shift + * @access private + */ + function _lshift($shift) + { + if ( $shift == 0 ) { + return; + } + + $num_digits = floor($shift / 26); + $shift %= 26; + $shift = 1 << $shift; + + $carry = 0; + + for ($i = 0; $i < count($this->value); $i++) { + $temp = $this->value[$i] * $shift + $carry; + $carry = floor($temp / 0x4000000); + $this->value[$i] = $temp - $carry * 0x4000000; + } + + if ( $carry ) { + $this->value[] = $carry; + } + + while ($num_digits--) { + array_unshift($this->value, 0); + } + } + + /** + * Logical Right Shift + * + * Shifts BigInteger's by $shift bits. + * + * @param Integer $shift + * @access private + */ + function _rshift($shift) + { + if ($shift == 0) { + $this->_normalize(); + } + + $num_digits = floor($shift / 26); + $shift %= 26; + $carry_shift = 26 - $shift; + $carry_mask = (1 << $shift) - 1; + + if ( $num_digits ) { + $this->value = array_slice($this->value, $num_digits); + } + + $carry = 0; + + for ($i = count($this->value) - 1; $i >= 0; $i--) { + $temp = $this->value[$i] >> $shift | $carry; + $carry = ($this->value[$i] & $carry_mask) << $carry_shift; + $this->value[$i] = $temp; + } + + $this->_normalize(); + } + + /** + * Normalize + * + * Deletes leading zeros. + * + * @see divide() + * @return Math_BigInteger + * @access private + */ + function _normalize() + { + if ( !count($this->value) ) { + return $this; + } + + for ($i=count($this->value) - 1; $i >= 0; $i--) { + if ( $this->value[$i] ) { + break; + } + unset($this->value[$i]); + } + + return $this; + } + + /** + * Array Repeat + * + * @param $input Array + * @param $multiplier mixed + * @return Array + * @access private + */ + function _array_repeat($input, $multiplier) + { + return ($multiplier) ? array_fill(0, $multiplier, $input) : array(); + } + + /** + * Logical Left Shift + * + * Shifts binary strings $shift bits, essentially multiplying by 2**$shift. + * + * @param $x String + * @param $shift Integer + * @return String + * @access private + */ + function _base256_lshift(&$x, $shift) + { + if ($shift == 0) { + return; + } + + $num_bytes = $shift >> 3; // eg. floor($shift/8) + $shift &= 7; // eg. $shift % 8 + + $carry = 0; + for ($i = strlen($x) - 1; $i >= 0; $i--) { + $temp = ord($x{$i}) << $shift | $carry; + $x{$i} = chr($temp); + $carry = $temp >> 8; + } + $carry = ($carry != 0) ? chr($carry) : ''; + $x = $carry . $x . str_repeat(chr(0), $num_bytes); + } + + /** + * Logical Right Shift + * + * Shifts binary strings $shift bits, essentially dividing by 2**$shift and returning the remainder. + * + * @param $x String + * @param $shift Integer + * @return String + * @access private + */ + function _base256_rshift(&$x, $shift) + { + if ($shift == 0) { + $x = ltrim($x, chr(0)); + return ''; + } + + $num_bytes = $shift >> 3; // eg. floor($shift/8) + $shift &= 7; // eg. $shift % 8 + + $remainder = ''; + if ($num_bytes) { + $start = $num_bytes > strlen($x) ? -strlen($x) : -$num_bytes; + $remainder = substr($x, $start); + $x = substr($x, 0, -$num_bytes); + } + + $carry = 0; + $carry_shift = 8-$shift; + for ($i = 0; $i < strlen($x); $i++) { + $temp = (ord($x{$i}) >> $shift) | $carry; + $carry = (ord($x{$i}) << $carry_shift) & 0xFF; + $x{$i} = chr($temp); + } + $x = ltrim($x, chr(0)); + + $remainder = chr($carry >> $carry_shift) . $remainder; + + return ltrim($remainder, chr(0)); + } + + // one quirk about how the following functions are implemented is that PHP defines N to be an unsigned long + // at 32-bits, while java's longs are 64-bits. + + /** + * Converts 32-bit integers to bytes. + * + * @param Integer $x + * @return String + * @access private + */ + function _int2bytes($x) + { + return ltrim(pack('N', $x), chr(0)); + } + + /** + * Converts bytes to 32-bit integers + * + * @param String $x + * @return Integer + * @access private + */ + function _bytes2int($x) + { + $temp = unpack('Nint', str_pad($x, 4, chr(0), STR_PAD_LEFT)); + return $temp['int']; + } +} + +// vim: ts=4:sw=4:et: +// vim6: fdl=1: +?> \ No newline at end of file diff --git a/phpseclib/Net/SSH1.php b/phpseclib/Net/SSH1.php new file mode 100644 index 00000000..e5ba2fa6 --- /dev/null +++ b/phpseclib/Net/SSH1.php @@ -0,0 +1,1126 @@ + + * login('username', 'password')) { + * exit('Login Failed'); + * } + * + * while (true) { + * echo $ssh->interactiveRead(); + * + * $read = array(STDIN); + * $write = $except = NULL; + * if (stream_select($read, $write, $except, 0)) { + * $ssh->interactiveWrite(fread(STDIN, 1)); + * } + * } + * ?> + * + * + * Here's another short example: + * + * login('username', 'password')) { + * exit('Login Failed'); + * } + * + * echo $ssh->writeReadQuit('ls -la'); + * ?> + * + * + * More information on the SSHv1 specification can be found by reading + * {@link http://web.archive.org/web/20010417045724/http://www.tigerlair.com/ssh/faq/ssh1-draft.txt ssh1-draft.txt}. + * + * LICENSE: This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + * + * @category Net + * @package Net_SSH1 + * @author Jim Wigginton + * @copyright MMVII Jim Wigginton + * @license http://www.gnu.org/licenses/lgpl.txt + * @version $Id: SSH1.php,v 1.1 2007-07-02 04:19:47 terrafrost Exp $ + * @link http://pear.php.net/package/Net_SSH1 + */ + +/** + * Include Math_BigInteger + * + * Used to do RSA encryption. + */ +require_once('Math/BigInteger.php'); + +/** + * Include Crypt_Null + */ +//require_once('Crypt/Null.php'); + +/** + * Include Crypt_DES + */ +require_once('Crypt/DES.php'); + +/** + * Include Crypt_TripleDES + */ +require_once('Crypt/TripleDES.php'); + +/** + * Include Crypt_RC4 + */ +require_once('Crypt/RC4.php'); + +/** + * Include Crypt_Random + */ +require_once('Crypt/Random.php'); + +/**#@+ + * Protocol Flags + * + * @access private + */ +define('NET_SSH1_MSG_DISCONNECT', 1); +define('NET_SSH1_SMSG_PUBLIC_KEY', 2); +define('NET_SSH1_CMSG_SESSION_KEY', 3); +define('NET_SSH1_CMSG_USER', 4); +define('NET_SSH1_CMSG_AUTH_PASSWORD', 9); +define('NET_SSH1_CMSG_REQUEST_PTY', 10); +define('NET_SSH1_CMSG_EXEC_SHELL', 12); +define('NET_SSH1_CMSG_EXEC_CMD', 13); +define('NET_SSH1_SMSG_SUCCESS', 14); +define('NET_SSH1_SMSG_FAILURE', 15); +define('NET_SSH1_CMSG_STDIN_DATA', 16); +define('NET_SSH1_SMSG_STDOUT_DATA', 17); +define('NET_SSH1_SMSG_STDERR_DATA', 18); +define('NET_SSH1_SMSG_EXITSTATUS', 20); +define('NET_SSH1_CMSG_EXIT_CONFIRMATION', 33); +/**#@-*/ + +/**#@+ + * Encryption Methods + * + * @see Net_SSH1::getSupportedCiphers() + * @access public + */ +/** + * No encryption + * + * Not supported. + */ +define('NET_SSH1_CIPHER_NONE', 0); +/** + * IDEA in CFB mode + * + * Not supported. + */ +define('NET_SSH1_CIPHER_IDEA', 1); +/** + * DES in CBC mode + */ +define('NET_SSH1_CIPHER_DES', 2); +/** + * Triple-DES in CBC mode + * + * All implementations are required to support this + */ +define('NET_SSH1_CIPHER_3DES', 3); +/** + * TRI's Simple Stream encryption CBC + * + * Not supported nor is it defined in the official SSH1 specs. OpenSSH, however, does define it (see cipher.h), + * although it doesn't use it (see cipher.c) + */ +define('NET_SSH1_CIPHER_BROKEN_TSS', 4); +/** + * RC4 + * + * Not supported. + * + * @internal According to the SSH1 specs: + * + * "The first 16 bytes of the session key are used as the key for + * the server to client direction. The remaining 16 bytes are used + * as the key for the client to server direction. This gives + * independent 128-bit keys for each direction." + * + * This library currently only supports encryption when the same key is being used for both directions. This is + * because there's only one $crypto object. Two could be added ($encrypt and $decrypt, perhaps). + */ +define('NET_SSH1_CIPHER_RC4', 5); +/** + * Blowfish + * + * Not supported nor is it defined in the official SSH1 specs. OpenSSH, however, defines it (see cipher.h) and + * uses it (see cipher.c) + */ +define('NET_SSH1_CIPHER_BLOWFISH', 6); +/**#@-*/ + +/**#@+ + * Authentication Methods + * + * @see Net_SSH1::getSupportedAuthentications() + * @access public + */ +/** + * .rhosts or /etc/hosts.equiv + */ +define('NET_SSH1_AUTH_RHOSTS', 1); +/** + * pure RSA authentication + */ +define('NET_SSH1_AUTH_RSA', 2); +/** + * password authentication + * + * This is the only method that is supported by this library. + */ +define('NET_SSH1_AUTH_PASSWORD', 3); +/** + * .rhosts with RSA host authentication + */ +define('NET_SSH1_AUTH_RHOSTS_RSA', 4); +/**#@-*/ + +/**#@+ + * Terminal Modes + * + * @link http://3sp.com/content/developer/maverick-net/docs/Maverick.SSH.PseudoTerminalModesMembers.html + * @access private + */ +define('NET_SSH1_TTY_OP_END', 0); +/**#@-*/ + +/** + * The Response Type + * + * @see Net_SSH1::_get_binary_packet() + * @access private + */ +define('NET_SSH1_RESPONSE_TYPE', 1); + +/** + * The Response Data + * + * @see Net_SSH1::_get_binary_packet() + * @access private + */ +define('NET_SSH1_RESPONSE_DATA', 2); + +/**#@+ + * Execution Bitmap Masks + * + * @see Net_SSH1::bitmap + * @access private + */ +define('NET_SSH1_MASK_CONSTRUCTOR', 0x00000001); +define('NET_SSH1_MASK_LOGIN', 0x00000002); +define('NET_SSH1_MASK_SHELL', 0x00000004); +/**#@-*/ + +/** + * Pure-PHP implementation of SSHv1. + * + * @author Jim Wigginton + * @version 0.1.0 + * @access public + * @package Net_SSH1 + */ +class Net_SSH1 { + /** + * The SSH identifier + * + * @var String + * @access private + */ + var $identifier = 'SSH-1.5-phpseclib'; + + /** + * The Socket Object + * + * @var Object + * @access private + */ + var $fsock; + + /** + * The cryptography object + * + * @var Object + * @access private + */ + var $crypto = false; + + /** + * Execution Bitmap + * + * The bits that are set reprsent functions that have been called already. This is used to determine + * if a requisite function has been successfully executed. If not, an error should be thrown. + * + * @var Boolean + * @access private + */ + var $bitmap = true; + + /** + * The Server Key Public Exponent + * + * Logged for debug purposes + * + * @see Net_SSH1::getServerKeyPublicExponent() + * @var String + * @access private + */ + var $server_key_public_exponent; + + /** + * The Server Key Public Modulus + * + * Logged for debug purposes + * + * @see Net_SSH1::getServerKeyPublicModulus() + * @var String + * @access private + */ + var $server_key_public_modulus; + + /** + * The Host Key Public Exponent + * + * Logged for debug purposes + * + * @see Net_SSH1::getHostKeyPublicExponent() + * @var String + * @access private + */ + var $host_key_public_exponent; + + /** + * The Host Key Public Modulus + * + * Logged for debug purposes + * + * @see Net_SSH1::getHostKeyPublicModulus() + * @var String + * @access private + */ + var $host_key_public_modulus; + + /** + * Supported Ciphers + * + * Logged for debug purposes + * + * @see Net_SSH1::getSupportedCiphers() + * @var Array + * @access private + */ + var $supported_ciphers = array( + NET_SSH1_CIPHER_NONE => 'No encryption', + NET_SSH1_CIPHER_IDEA => 'IDEA in CFB mode', + NET_SSH1_CIPHER_DES => 'DES in CBC mode', + NET_SSH1_CIPHER_3DES => 'Triple-DES in CBC mode', + NET_SSH1_CIPHER_BROKEN_TSS => 'TRI\'s Simple Stream encryption CBC', + NET_SSH1_CIPHER_RC4 => 'RC4', + NET_SSH1_CIPHER_BLOWFISH => 'Blowfish' + ); + + /** + * Supported Authentications + * + * Logged for debug purposes + * + * @see Net_SSH1::getSupportedAuthentications() + * @var Array + * @access private + */ + var $supported_authentications = array( + NET_SSH1_AUTH_RHOSTS => '.rhosts or /etc/hosts.equiv', + NET_SSH1_AUTH_RSA => 'pure RSA authentication', + NET_SSH1_AUTH_PASSWORD => 'password authentication', + NET_SSH1_AUTH_RHOSTS_RSA => '.rhosts with RSA host authentication' + ); + + /** + * Server Identification + * + * @see Net_SSH1::getServerIdentification() + * @var String + * @access private + */ + var $server_identification = ''; + + /** + * Default Constructor. + * + * Connects to an SSHv1 server + * + * @param String $host + * @param optional Integer $port + * @param optional Integer $cipher + * @return Net_SSH1 + * @access public + */ + function Net_SSH1($host, $port = 22, $cipher = NET_SSH1_CIPHER_3DES) + { + $this->fsock = fsockopen($host, $port, $errno, $errstr, 10); + if (!$this->fsock) { + user_error(rtrim("Cannot connect to $host. Error $errno. $errstr"), E_USER_NOTICE); + return; + } + + $this->server_identification = $init_line = fgets($this->fsock, 255); + if (!preg_match('#SSH-([0-9\.]+)-(.+)#', $init_line, $parts)) { + user_error('Can only connect to SSH servers', E_USER_NOTICE); + return; + } + if ($parts[1][0] != 1) { + user_error("Cannot connect to SSH $parts[1] servers", E_USER_NOTICE); + return; + } + + fputs($this->fsock, $this->identifier."\r\n"); + + $response = $this->_get_binary_packet(); + if ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_PUBLIC_KEY) { + user_error('Expected SSH_SMSG_PUBLIC_KEY', E_USER_NOTICE); + return; + } + + $anti_spoofing_cookie = $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 8); + + $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4); + + $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2)); + $server_key_public_exponent = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256); + $this->server_key_public_exponent = $server_key_public_exponent; + + $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2)); + $server_key_public_modulus = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256); + $this->server_key_public_modulus = $server_key_public_modulus; + + $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4); + + $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2)); + $host_key_public_exponent = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256); + $this->host_key_public_exponent = $host_key_public_exponent; + + $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2)); + $host_key_public_modulus = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256); + $this->host_key_public_modulus = $host_key_public_modulus; + + $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4); + + // get a list of the supported ciphers + list(, $supported_ciphers_mask) = unpack('N', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4)); + foreach ($this->supported_ciphers as $mask=>$name) { + if (($supported_ciphers_mask & (1 << $mask)) == 0) { + unset($this->supported_ciphers[$mask]); + } + } + + // get a list of the supported authentications + list(, $supported_authentications_mask) = unpack('N', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4)); + foreach ($this->supported_authentications as $mask=>$name) { + if (($supported_authentications_mask & (1 << $mask)) == 0) { + unset($this->supported_authentications[$mask]); + } + } + + $session_id = pack('H*', md5($host_key_public_modulus->toBytes() . $server_key_public_modulus->toBytes() . $anti_spoofing_cookie)); + + $session_key = ''; + for ($i = 0; $i < 32; $i++) { + $session_key.= chr(crypt_random(0, 255)); + } + $double_encrypted_session_key = $session_key ^ str_pad($session_id, 32, chr(0)); + + if ($server_key_public_modulus->compare($host_key_public_modulus) < 0) { + $double_encrypted_session_key = $this->_rsa_crypt( + $double_encrypted_session_key, + array( + $server_key_public_exponent, + $server_key_public_modulus + ) + ); + $double_encrypted_session_key = $this->_rsa_crypt( + $double_encrypted_session_key, + array( + $host_key_public_exponent, + $host_key_public_modulus + ) + ); + } else { + $double_encrypted_session_key = $this->_rsa_crypt( + $double_encrypted_session_key, + array( + $host_key_public_exponent, + $host_key_public_modulus + ) + ); + $double_encrypted_session_key = $this->_rsa_crypt( + $double_encrypted_session_key, + array( + $server_key_public_exponent, + $server_key_public_modulus + ) + ); + } + + $cipher = isset($this->supported_ciphers[$cipher]) ? $cipher : NET_SSH1_CIPHER_3DES; + $data = pack('C2a*na*N', NET_SSH1_CMSG_SESSION_KEY, $cipher, $anti_spoofing_cookie, 8 * strlen($double_encrypted_session_key), $double_encrypted_session_key, 0); + + if (!$this->_send_binary_packet($data)) { + user_error('Error sending SSH_CMSG_SESSION_KEY', E_USER_NOTICE); + return; + } + + switch ($cipher) { + //case NET_SSH1_CIPHER_NONE: + // $this->crypto = new Crypt_Null(); + // break; + case NET_SSH1_CIPHER_DES: + $this->crypto = new Crypt_DES(); + $this->crypto->disablePadding(); + $this->crypto->enableContinuousBuffer(); + $this->crypto->setKey(substr($session_key, 0, 8)); + break; + case NET_SSH1_CIPHER_3DES: + $this->crypto = new Crypt_TripleDES(CRYPT_DES_MODE_SSH); + $this->crypto->setKey(substr($session_key, 0, 24)); + break; + //case NET_SSH1_CIPHER_RC4: + // $this->crypto = new Crypt_RC4(); + // $this->crypto->enableContinuousBuffer(); + // $this->crypto->setKey(substr($session_key, 0, 16)); + // break; + } + + $response = $this->_get_binary_packet(); + + if ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_SUCCESS) { + user_error('Expected SSH_SMSG_SUCCESS', E_USER_NOTICE); + return; + } + + $this->bitmap = NET_SSH1_MASK_CONSTRUCTOR; + } + + /** + * Login + * + * @param String $username + * @param optional String $password + * @return Boolean + * @access public + */ + function login($username, $password = '') + { + if (!($this->bitmap & NET_SSH1_MASK_CONSTRUCTOR)) { + return false; + } + + $data = pack('CNa*', NET_SSH1_CMSG_USER, strlen($username), $username); + + if (!$this->_send_binary_packet($data)) { + user_error('Error sending SSH_CMSG_USER', E_USER_NOTICE); + return false; + } + + $response = $this->_get_binary_packet(); + + if ($response[NET_SSH1_RESPONSE_TYPE] == NET_SSH1_SMSG_SUCCESS) { + $this->bitmap |= NET_SSH1_MASK_LOGIN; + return true; + } else if ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_FAILURE) { + user_error('Expected SSH_SMSG_SUCCESS or SSH_SMSG_FAILURE', E_USER_NOTICE); + return false; + } + + $data = pack('CNa*', NET_SSH1_CMSG_AUTH_PASSWORD, strlen($password), $password); + + if (!$this->_send_binary_packet($data)) { + user_error('Error sending SSH_CMSG_AUTH_PASSWORD', E_USER_NOTICE); + return false; + } + + $response = $this->_get_binary_packet(); + + if ($response[NET_SSH1_RESPONSE_TYPE] == NET_SSH1_SMSG_SUCCESS) { + $this->bitmap |= NET_SSH1_MASK_LOGIN; + return true; + } else if ($response[NET_SSH1_RESPONSE_TYPE] == NET_SSH1_SMSG_FAILURE) { + return false; + } else { + user_error('Expected SSH_SMSG_SUCCESS or SSH_SMSG_FAILURE', E_USER_NOTICE); + return false; + } + } + + /** + * Executes a command on a non-interactive shell, returns the output, and quits. + * + * An SSH1 server will close the connection after a command has been executed on a non-interactive shell. SSH2 + * servers don't, however, this isn't an SSH2 client. The way this works, on the server, is by initiating a + * shell with the -s option, as discussed in the following links: + * + * {@link http://www.faqs.org/docs/bashman/bashref_65.html http://www.faqs.org/docs/bashman/bashref_65.html} + * {@link http://www.faqs.org/docs/bashman/bashref_62.html http://www.faqs.org/docs/bashman/bashref_65.html} + * + * To execute further commands, a new Net_SSH1 object will need to be created. + * + * Returns false on failure and the output, otherwise. + * + * @see Net_SSH1::interactiveRead() + * @see Net_SSH1::interactiveWrite() + * @param String $cmd + * @return mixed + * @access public + */ + function writeReadQuit($cmd) + { + if (!($this->bitmap & NET_SSH1_MASK_LOGIN)) { + user_error('Operation disallowed prior to login()', E_USER_NOTICE); + return false; + } + + // connect using the sample parameters in ssh1-draft.txt. + // according to wikipedia.org's entry on text terminals, "the fundamental type of application running on a text + // terminal is a command line interpreter or shell". thus, opening a terminal session to run the shell. + $data = pack('CNa*N4C', NET_SSH1_CMSG_REQUEST_PTY, strlen('vt100'), 'vt100', 24, 80, 0, 0, NET_SSH1_TTY_OP_END); + + if (!$this->_send_binary_packet($data)) { + user_error('Error sending SSH_CMSG_REQUEST_PTY', E_USER_NOTICE); + return false; + } + + $response = $this->_get_binary_packet(); + + if ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_SUCCESS) { + user_error('Expected SSH_SMSG_SUCCESS', E_USER_NOTICE); + return false; + } + + $data = pack('CNa*', NET_SSH1_CMSG_EXEC_CMD, strlen($cmd), $cmd); + + if (!$this->_send_binary_packet($data)) { + user_error('Error sending SSH_CMSG_EXEC_CMD', E_USER_NOTICE); + return false; + } + + $output = ''; + $response = $this->_get_binary_packet(); + + do { + $output.= substr($response[NET_SSH1_RESPONSE_DATA], 4); + $response = $this->_get_binary_packet(); + } while ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_EXITSTATUS); + + $data = pack('C', NET_SSH1_CMSG_EXIT_CONFIRMATION); + + // i don't think it's really all that important if this packet gets sent or not. + $this->_send_binary_packet($data); + + fclose($this->fsock); + + // reset the execution bitmap - a new Net_SSH1 object needs to be created. + $this->bitmap = 0; + + return $output; + } + + /** + * Creates an interactive shell + * + * @see Net_SSH1::interactiveRead() + * @see Net_SSH1::interactiveWrite() + * @return Boolean + * @access private + */ + function _initShell() + { + $data = pack('CNa*N4C', NET_SSH1_CMSG_REQUEST_PTY, strlen('vt100'), 'vt100', 24, 80, 0, 0, NET_SSH1_TTY_OP_END); + + if (!$this->_send_binary_packet($data)) { + user_error('Error sending SSH_CMSG_REQUEST_PTY', E_USER_NOTICE); + return false; + } + + $response = $this->_get_binary_packet(); + + if ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_SUCCESS) { + user_error('Expected SSH_SMSG_SUCCESS', E_USER_NOTICE); + return false; + } + + $data = pack('C', NET_SSH1_CMSG_EXEC_SHELL); + + if (!$this->_send_binary_packet($data)) { + user_error('Error sending SSH_CMSG_EXEC_SHELL', E_USER_NOTICE); + return false; + } + + $this->bitmap |= NET_SSH1_MASK_SHELL; + + //stream_set_blocking($this->fsock, 0); + + return true; + } + + /** + * Inputs a command into an interactive shell. + * + * @see Net_SSH1::interactiveRead() + * @param String $cmd + * @return Boolean + * @access public + */ + function interactiveWrite($cmd) + { + if (!($this->bitmap & NET_SSH1_MASK_LOGIN)) { + user_error('Operation disallowed prior to login()', E_USER_NOTICE); + return false; + } + + if (!($this->bitmap & NET_SSH1_MASK_SHELL) && !$this->_initShell()) { + user_error('Unable to initiate an interactive shell session', E_USER_NOTICE); + return false; + } + + $data = pack('CNa*', NET_SSH1_CMSG_STDIN_DATA, strlen($cmd), $cmd); + + if (!$this->_send_binary_packet($data)) { + user_error('Error sending SSH_CMSG_STDIN', E_USER_NOTICE); + return false; + } + + return true; + } + + /** + * Reads the output of an interactive shell. + * + * Requires PHP 4.3.0 or later due to the use of the stream_select() function. If you see stuff like + * "", you're seeing ANSI escape codes. According to + * {@link http://support.microsoft.com/kb/101875 How to Enable ANSI.SYS in a Command Window}, "Windows NT + * does not support ANSI escape sequences in Win32 Console applications", so if you're a Windows user, + * there's not going to be much recourse. + * + * @see Net_SSH1::interactiveRead() + * @param String $cmd + * @return Boolean + * @access public + */ + function interactiveRead() + { + if (!($this->bitmap & NET_SSH1_MASK_LOGIN)) { + user_error('Operation disallowed prior to login()', E_USER_NOTICE); + return false; + } + + if (!($this->bitmap & NET_SSH1_MASK_SHELL) && !$this->_initShell()) { + user_error('Unable to initiate an interactive shell session', E_USER_NOTICE); + return false; + } + + $read = array($this->fsock); + $write = $except = null; + if (stream_select($read, $write, $except, 0)) { + $response = $this->_get_binary_packet(); + return substr($response[NET_SSH1_RESPONSE_DATA], 4); + } else { + return ''; + } + } + + /** + * Disconnects. + * + * Will be called, automatically, if you're using PHP5. If you're using PHP4, call it yourself. + * + * @access public + */ + function __destruct() + { + if ($this->bitmap) { + $msg = 'Client Quit'; + $data = pack('CNa*', NET_SSH1_MSG_DISCONNECT, strlen($msg), $msg); + $this->_send_binary_packet($data); + fclose($this->fsock); + $this->bitmap = 0; + } + } + + /** + * Gets Binary Packets + * + * See 'The Binary Packet Protocol' of ssh1-draft.txt for more info. + * + * Also, this function could be improved upon by adding detection for the following exploit: + * http://www.securiteam.com/securitynews/5LP042K3FY.html + * + * @see Net_SSH1::_send_binary_packet() + * @return Array + * @access private + */ + function _get_binary_packet() + { + if (feof($this->fsock)) { + //user_error('connection closed prematurely', E_USER_NOTICE); + return false; + } + + $temp = unpack('Nlength', fread($this->fsock, 4)); + + $padding_length = 8 - ($temp['length'] & 7); + $length = $temp['length'] + $padding_length; + + $raw = fread($this->fsock, $length); + + if ($this->crypto !== false) { + $raw = $this->crypto->decrypt($raw); + } + + $padding = substr($raw, 0, $padding_length); + $type = $raw[$padding_length]; + $data = substr($raw, $padding_length + 1, -4); + + $temp = unpack('Ncrc', substr($raw, -4)); + + //if ( $temp['crc'] != $this->_crc($padding . $type . $data) ) { + // user_error('Bad CRC in packet from server', E_USER_NOTICE); + // return false; + //} + + return array( + NET_SSH1_RESPONSE_TYPE => ord($type), + NET_SSH1_RESPONSE_DATA => $data + ); + } + + /** + * Sends Binary Packets + * + * Returns true on success, false on failure. + * + * @see Net_SSH1::_get_binary_packet() + * @param String $data + * @return Boolean + * @access private + */ + function _send_binary_packet($data) { + if (feof($this->fsock)) { + //user_error('connection closed prematurely', E_USER_NOTICE); + return false; + } + + $length = strlen($data) + 4; + + $padding_length = 8 - ($length & 7); + $padding = ''; + for ($i = 0; $i < $padding_length; $i++) { + $padding.= chr(crypt_random(0, 255)); + } + + $data = $padding . $data; + $data.= pack('N', $this->_crc($data)); + + if ($this->crypto !== false) { + $data = $this->crypto->encrypt($data); + } + + $packet = pack('Na*', $length, $data); + + return strlen($packet) == fputs($this->fsock, $packet); + } + + /** + * Cyclic Redundancy Check (CRC) + * + * PHP's crc32 function is implemented slightly differently than the one that SSH v1 uses, so + * we've reimplemented it. A more detailed discussion of the differences can be found after + * $crc_lookup_table's initialization. + * + * @see Net_SSH1::_get_binary_packet() + * @see Net_SSH1::_send_binary_packet() + * @param String $data + * @return Integer + * @access private + */ + function _crc($data) + { + static $crc_lookup_table = array( + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, + 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, + 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, + 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, + 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, + 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, + 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, + 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, + 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, + 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, + 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, + 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, + 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, + 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, + 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, + 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, + 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, + 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, + 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, + 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, + 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, + 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, + 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, + 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, + 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, + 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, + 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, + 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, + 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, + 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, + 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, + 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, + 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, + 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, + 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, + 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, + 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, + 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, + 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, + 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, + 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, + 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, + 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, + 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, + 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, + 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, + 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, + 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, + 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, + 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, + 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, + 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, + 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, + 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, + 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, + 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, + 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, + 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, + 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, + 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D + ); + + // For this function to yield the same output as PHP's crc32 function, $crc would have to be + // set to 0xFFFFFFFF, initially - not 0x00000000 as it currently is. + $crc = 0x00000000; + $length = strlen($data); + + for ($i=0;$i<$length;$i++) { + // We AND $crc >> 8 with 0x00FFFFFF because we want the eight newly added bits to all + // be zero. PHP, unfortunately, doesn't always do this. 0x80000000 >> 8, as an example, + // yields 0xFF800000 - not 0x00800000. The following link elaborates: + // http://www.php.net/manual/en/language.operators.bitwise.php#57281 + $crc = (($crc >> 8) & 0x00FFFFFF) ^ $crc_lookup_table[($crc & 0xFF) ^ ord($data[$i])]; + } + + // In addition to having to set $crc to 0xFFFFFFFF, initially, the return value must be XOR'd with + // 0xFFFFFFFF for this function to return the same thing that PHP's crc32 function would. + return $crc; + } + + /** + * String Shift + * + * Inspired by array_shift + * + * @param String $string + * @param optional Integer $index + * @return String + * @access private + */ + function _string_shift(&$string, $index = 1) + { + $substr = substr($string, 0, $index); + $string = substr($string, $index); + return $substr; + } + + /** + * RSA Encrypt + * + * Returns mod(pow($m, $e), $n), where $n should be the product of two (large) primes $p and $q and where $e + * should be a number with the property that gcd($e, ($p - 1) * ($q - 1)) == 1. Could just make anything that + * calls this call modexp, instead, but I think this makes things clearer, maybe... + * + * @see Net_SSH1::Net_SSH1() + * @param Math_BigInteger $m + * @param Array $key + * @return Math_BigInteger + * @access private + */ + function _rsa_crypt($m, $key) + { + // To quote from ssh1-draft.txt: + // The most significant byte (which is only partial as the value must be + // less than the public modulus, which is never a power of two) is zero. + // + // The next byte contains the value 2 (which stands for public-key + // encrypted data in the PKCS standard [PKCS#1]). Then, there are non- + // zero random bytes to fill any unused space, a zero byte, and the data + // to be encrypted in the least significant bytes, the last byte of the + // data in the least significant byte. + + // Presumably the part of PKCS#1 they're refering to is "Section 7.2.1 Encryption Operation", + // under "7.2 RSAES-PKCS1-v1.5" and "7 Encryption schemes" of the following URL: + // ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1.pdf + $temp = chr(0) . chr(2); + $modulus = $key[1]->toBytes(); + $length = strlen($modulus) - strlen($m) - 3; + for ($i = 0; $i < $length; $i++) { + $temp.= chr(crypt_random(1, 255)); + } + $temp.= chr(0) . $m; + + $m = new Math_BigInteger($temp, 256); + $m = $m->modPow($key[0], $key[1]); + + return $m->toBytes(); + } + + /** + * Return the server key public exponent + * + * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead, + * the raw bytes. This behavior is similar to PHP's md5() function. + * + * @param optional Boolean $raw_output + * @return String + * @access public + */ + function getServerKeyPublicExponent($raw_output = false) + { + return $raw_output ? $this->server_key_public_exponent->toBytes() : $this->server_key_public_exponent->toString(); + } + + /** + * Return the server key public modulus + * + * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead, + * the raw bytes. This behavior is similar to PHP's md5() function. + * + * @param optional Boolean $raw_output + * @return String + * @access public + */ + function getServerKeyPublicModulus($raw_output = false) + { + return $raw_output ? $this->server_key_public_modulus->toBytes() : $this->server_key_public_modulus->toString(); + } + + /** + * Return the host key public exponent + * + * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead, + * the raw bytes. This behavior is similar to PHP's md5() function. + * + * @param optional Boolean $raw_output + * @return String + * @access public + */ + function getHostKeyPublicExponent($raw_output = false) + { + return $raw_output ? $this->host_key_public_exponent->toBytes() : $this->host_key_public_exponent->toString(); + } + + /** + * Return the host key public modulus + * + * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead, + * the raw bytes. This behavior is similar to PHP's md5() function. + * + * @param optional Boolean $raw_output + * @return String + * @access public + */ + function getHostKeyPublicModulus($raw_output = false) + { + return $raw_output ? $this->host_key_public_modulus->toBytes() : $this->host_key_public_modulus->toString(); + } + + /** + * Return a list of ciphers supported by SSH1 server. + * + * Just because a cipher is supported by an SSH1 server doesn't mean it's supported by this library. If $raw_output + * is set to true, returns, instead, an array of constants. ie. instead of array('Triple-DES in CBC mode'), you'll + * get array(NET_SSH1_CIPHER_3DES). + * + * @param optional Boolean $raw_output + * @return Array + * @access public + */ + function getSupportedCiphers($raw_output = false) + { + return $raw_output ? array_keys($this->supported_ciphers) : array_values($this->supported_ciphers); + } + + /** + * Return a list of authentications supported by SSH1 server. + * + * Just because a cipher is supported by an SSH1 server doesn't mean it's supported by this library. If $raw_output + * is set to true, returns, instead, an array of constants. ie. instead of array('password authentication'), you'll + * get array(NET_SSH1_AUTH_PASSWORD). + * + * @param optional Boolean $raw_output + * @return Array + * @access public + */ + function getSupportedAuthentications($raw_output = false) + { + return $raw_output ? array_keys($this->supported_authentications) : array_values($this->supported_authentications); + } + + /** + * Return the server identification. + * + * @return String + * @access public + */ + function getServerIdentification() + { + return rtrim($this->server_identification); + } +} +?> \ No newline at end of file diff --git a/phpseclib/PHP/Compat/Function/array_fill.php b/phpseclib/PHP/Compat/Function/array_fill.php new file mode 100644 index 00000000..c6038357 --- /dev/null +++ b/phpseclib/PHP/Compat/Function/array_fill.php @@ -0,0 +1,43 @@ +, Arpad Ray + * @link http://php.net/function.array_fill + * @author Jim Wigginton + * @version $Revision: 1.1 $ + * @since PHP 4.2.0 + */ +function php_compat_array_fill($start_index, $num, $value) +{ + if ($num <= 0) { + user_error('array_fill(): Number of elements must be positive', E_USER_WARNING); + + return false; + } + + $temp = array(); + + $end_index = $start_index + $num; + for ($i = (int) $start_index; $i < $end_index; $i++) { + $temp[$i] = $value; + } + + return $temp; +} + +// Define +if (!function_exists('array_fill')) { + function array_fill($start_index, $num, $value) + { + return php_compat_array_fill($start_index, $num, $value); + } +} + +?> \ No newline at end of file diff --git a/phpseclib/PHP/Compat/Function/bcpowmod.php b/phpseclib/PHP/Compat/Function/bcpowmod.php new file mode 100644 index 00000000..da165586 --- /dev/null +++ b/phpseclib/PHP/Compat/Function/bcpowmod.php @@ -0,0 +1,67 @@ +, Arpad Ray + * @link http://php.net/function.bcpowmod + * @author Sara Golemon + * @version $Revision: 1.1 $ + * @since PHP 5.0.0 + * @require PHP 4.0.0 (user_error) + */ +function php_compat_bcpowmod($x, $y, $modulus, $scale = 0) +{ + // Sanity check + if (!is_scalar($x)) { + user_error('bcpowmod() expects parameter 1 to be string, ' . + gettype($x) . ' given', E_USER_WARNING); + return false; + } + + if (!is_scalar($y)) { + user_error('bcpowmod() expects parameter 2 to be string, ' . + gettype($y) . ' given', E_USER_WARNING); + return false; + } + + if (!is_scalar($modulus)) { + user_error('bcpowmod() expects parameter 3 to be string, ' . + gettype($modulus) . ' given', E_USER_WARNING); + return false; + } + + if (!is_scalar($scale)) { + user_error('bcpowmod() expects parameter 4 to be integer, ' . + gettype($scale) . ' given', E_USER_WARNING); + return false; + } + + $t = '1'; + while (bccomp($y, '0')) { + if (bccomp(bcmod($y, '2'), '0')) { + $t = bcmod(bcmul($t, $x), $modulus); + $y = bcsub($y, '1'); + } + + $x = bcmod(bcmul($x, $x), $modulus); + $y = bcdiv($y, '2'); + } + + return $t; +} + + +// Define +if (!function_exists('bcpowmod')) { + function bcpowmod($x, $y, $modulus, $scale = 0) + { + return php_compat_bcpowmod($x, $y, $modulus, $scale); + } +} +?> \ No newline at end of file