/** * @param $pem_format * @param string $password * @throws RSABadPEMFormat */ public function __construct($pem_format, $password = null) { parent::__construct($pem_format, $password); $this->d = $this->rsa_imp->exponent; if ($this->d->toString() === $this->e->toString()) { throw new RSABadPEMFormat(sprintf('pem %s is a public key!', $pem_format)); } }
public function add1($pos, $value, $sid) { if ($pos < $this->size()) { $tmp1 = new Math_BigInteger($this->get($pos)->getInt()); $tmp = $tmp1->add($value); unset($this->mPosition[$pos]); $this->mPosition[$pos] = new LogootId($tmp->toString(), $sid); } else { $this->mPosition[] = new LogootId($tmp->toString(), $sid); } }
function ssh1_connect($host, $port) { $identifier = 'SSH-1.5-' . basename(__FILE__); $fsock = fsockopen($host, $port, $errno, $errstr, 10); if (!$fsock) { die("Error {$errno}: {$errstr}"); } $init_line = fgets($fsock, 255); if (!preg_match('#SSH-([0-9\\.]+)-(.+)#', $init_line, $parts)) { die('Not an SSH server on the other side.'); } if ($parts[1][0] != 1) { die("SSH version {$parts[1]} is not supported!"); } echo "Connecting to {$init_line}\r\n"; fputs($fsock, "{$identifier}\n"); $packet = get_binary_packet($fsock); if ($packet['type'] != SSH_SMSG_PUBLIC_KEY) { die('Expected SSH_SMSG_PUBLIC_KEY!'); } $anti_spoofing_cookie = string_shift($packet['data'], 8); string_shift($packet['data'], 4); $temp = unpack('nlen', string_shift($packet['data'], 2)); $server_key_public_exponent = new Math_BigInteger(string_shift($packet['data'], ceil($temp['len'] / 8)), 256); $temp = unpack('nlen', string_shift($packet['data'], 2)); $server_key_public_modulus = new Math_BigInteger(string_shift($packet['data'], ceil($temp['len'] / 8)), 256); $temp = unpack('nlen', string_shift($packet['data'], 2)); $host_key_public_exponent = new Math_BigInteger(string_shift($packet['data'], ceil($temp['len'] / 8)), 256); $temp = unpack('nlen', string_shift($packet['data'], 2)); $host_key_public_modulus = new Math_BigInteger(string_shift($packet['data'], ceil($temp['len'] / 8)), 256); $session_id = pack('H*', md5($host_key_public_modulus . $server_key_public_modulus . $anti_spoofing_cookie)); // ought to use a cryptographically secure random number generator (which mt_srand is not) list($sec, $usec) = explode(' ', microtime()); mt_srand((double) $sec + (double) $usec * 100000); $session_key = ''; for ($i = 0; $i < 32; $i++) { $session_key .= chr(mt_rand(0, 255)); } $double_encrypted_session_key = $session_key ^ str_pad($session_id, 32, chr(0)); echo "starting rsa encryption\r\n\r\n"; if ($server_key_public_modulus->compare($host_key_public_modulus) < 0) { $prepped_key = prep_session_key($double_encrypted_session_key, $server_key_public_modulus); rsa_crypt($prepped_key, array($server_key_public_exponent, $server_key_public_modulus)); rsa_crypt2($prepped_key, array($server_key_public_exponent, $server_key_public_modulus)); } else { $prepped_key = prep_session_key($double_encrypted_session_key, $host_key_public_modulus); rsa_crypt($prepped_key, array($host_key_public_exponent, $host_key_public_modulus)); rsa_crypt2($prepped_key, array($host_key_public_exponent, $host_key_public_modulus)); } }
/** * @param string $decimal 128bit int * @return string IPv4 or IPv6 */ public static function inet_itop($decimal) { // QuickFix: Decimal 0 is both for ::0 and 0.0.0.0, however it defaults to IPv6, while there is now way a // ::/64 will ever be used. if ($decimal < 255) { return '0.0.0.' . $decimal; } $parts = array(); // Use BCMath if available if (function_exists('bcadd')) { $parts[1] = bcdiv($decimal, '79228162514264337593543950336', 0); $decimal = bcsub($decimal, bcmul($parts[1], '79228162514264337593543950336')); $parts[2] = bcdiv($decimal, '18446744073709551616', 0); $decimal = bcsub($decimal, bcmul($parts[2], '18446744073709551616')); $parts[3] = bcdiv($decimal, '4294967296', 0); $decimal = bcsub($decimal, bcmul($parts[3], '4294967296')); $parts[4] = $decimal; } else { // Otherwise use the pure PHP BigInteger class $decimal = new Math_BigInteger($decimal); list($parts[1], ) = $decimal->divide(new Math_BigInteger('79228162514264337593543950336')); $decimal = $decimal->subtract($parts[1]->multiply(new Math_BigInteger('79228162514264337593543950336'))); list($parts[2], ) = $decimal->divide(new Math_BigInteger('18446744073709551616')); $decimal = $decimal->subtract($parts[2]->multiply(new Math_BigInteger('18446744073709551616'))); list($parts[3], ) = $decimal->divide(new Math_BigInteger('4294967296')); $decimal = $decimal->subtract($parts[3]->multiply(new Math_BigInteger('4294967296'))); $parts[4] = $decimal; $parts[1] = $parts[1]->toString(); $parts[2] = $parts[2]->toString(); $parts[3] = $parts[3]->toString(); $parts[4] = $parts[4]->toString(); } foreach ($parts as &$part) { // convert any signed ints to unsigned for pack // this should be fine as it will be treated as a float if ($part > 2147483647) { $part -= 4294967296.0; } } $ip = inet_ntop(pack('N4', $parts[1], $parts[2], $parts[3], $parts[4])); // fix IPv4 by removing :: from the beginning if (strpos($ip, '.') !== false) { return substr($ip, 2); } return $ip; }
protected static function make64Int($hi, $lo) { if (PHP_INT_SIZE > 4) { return (int) $hi << 32 | (int) $lo; } $lo = sprintf("%u", $lo); if (function_exists("gmp_mul")) { return gmp_strval(gmp_add(gmp_mul($hi, "4294967296"), $lo)); } if (function_exists("bcmul")) { return bcadd(bcmul($hi, "4294967296"), $lo); } if (class_exists('Math_BigInteger')) { $bi = new Math_BigInteger($hi); return $bi->multiply("4294967296")->add($lo)->toString(); } throw new PListException("either gmp or bc has to be installed, or the Math_BigInteger has to be available!"); }
function decrypt($val) { # Support for both obfuscated and unobfuscated passwords $encryptionstr = 'Encrypted '; if (strstr($val, $encryptionstr)) { $val = substr($val, strlen($encryptionstr)); } else { return $val; } # decryption logic $decconst = new Math_BigInteger('933910847463829827159347601486730416058'); $decrparam = new Math_BigInteger($val, 16); $decryptedval = $decrparam->bitwise_xor($decconst)->toBytes(); $result = ""; for ($i = 0; $i < strlen($decryptedval); $i = $i + 1) { $result .= $decryptedval[$i]; } return $result; }
public function compareTo($id) { $logid = $id; $val1 = new Math_BigInteger($this->mInt); $val2 = new Math_BigInteger($logid->mInt); if ($val1->compare($val2) < 0) { return -1; } else { if ($val1->compare($val2) > 0) { return 1; } else { if (strcmp($this->mSessionId, $logid->mSessionId) < 0) { return -1; } else { if (strcmp($this->mSessionId, $logid->mSessionId) > 0) { return 1; } } } } return 0; }
/** * @param string $ip IPv4 or IPv6 address to convert * * @return string 128bit string that can be used with DECIMNAL(39,0) or false */ function inetPtoi($ip) { // make sure it is an ip if (filter_var($ip, FILTER_VALIDATE_IP) === false) { return false; } $parts = unpack('N*', inet_pton($ip)); // fix IPv4 if (strpos($ip, '.') !== false) { $parts = [1 => 0, 2 => 0, 3 => 0, 4 => $parts[1]]; } foreach ($parts as &$part) { // convert any unsigned ints to signed from unpack. // this should be OK as it will be a PHP float not an int if ($part < 0) { $part = 4294967296; } } if (function_exists('bcadd')) { // Use BCMath if available $decimal = $parts[4]; $decimal = bcadd($decimal, bcmul($parts[3], '4294967296')); $decimal = bcadd($decimal, bcmul($parts[2], '18446744073709551616')); $decimal = bcadd($decimal, bcmul($parts[1], '79228162514264337593543950336')); } else { // Otherwise use the pure PHP BigInteger class $decimal = new Math_BigInteger($parts[4]); $partTree = new Math_BigInteger($parts[3]); $partTwo = new Math_BigInteger($parts[2]); $partOne = new Math_BigInteger($parts[1]); $decimal = $decimal->add($partTree->multiply(new Math_BigInteger('4294967296'))); $decimal = $decimal->add($partTwo->multiply(new Math_BigInteger('18446744073709551616'))); $decimal = $decimal->add($partOne->multiply(new Math_BigInteger('79228162514264337593543950336'))); $decimal = $decimal->toString(); } return $decimal; }
/** * Logical Exclusive-Or * * @param Math_BigInteger $x * @access public * @internal Implemented per a request by Lluis Pamies i Juarez <lluis _a_ pamies.cat> * @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(); }
/** * Generate a random prime number. * * If there's not a prime within the given range, false will be returned. If more than $timeout seconds have elapsed, * give up and return false. * * @param optional Integer $min * @param optional Integer $max * @param optional Integer $timeout * @return Math_BigInteger * @access public * @internal See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf#page=15 HAC 4.44}. */ function randomPrime($min = false, $max = false, $timeout = false) { // gmp_nextprime() requires PHP 5 >= 5.2.0 per <http://php.net/gmp-nextprime>. if (MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_GMP && function_exists('gmp_nextprime')) { // we don't rely on Math_BigInteger::random()'s min / max when gmp_nextprime() is being used since this function // does its own checks on $max / $min when gmp_nextprime() is used. When gmp_nextprime() is not used, however, // the same $max / $min checks are not performed. 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; } } $x = $this->random($min, $max); $x->value = gmp_nextprime($x->value); if ($x->compare($max) <= 0) { return $x; } $x->value = gmp_nextprime($min->value); if ($x->compare($max) <= 0) { return $x; } return false; } $repeat1 = $repeat2 = array(); $one = new Math_BigInteger(1); $two = new Math_BigInteger(2); $start = time(); do { if ($timeout !== false && time() - $start > $timeout) { return false; } $x = $this->random($min, $max); if ($x->equals($two)) { return $x; } // make the number odd switch (MATH_BIGINTEGER_MODE) { case MATH_BIGINTEGER_MODE_GMP: gmp_setbit($x->value, 0); break; case MATH_BIGINTEGER_MODE_BCMATH: if ($x->value[strlen($x->value) - 1] % 2 == 0) { $x = $x->add($one); } break; default: $x->value[0] |= 1; } // if we've seen this number twice before, assume there are no prime numbers within the given range if (in_array($x->value, $repeat1)) { if (in_array($x->value, $repeat2)) { return false; } else { $repeat2[] = $x->value; } } else { $repeat1[] = $x->value; } } while (!$x->isPrime()); return $x; }
/** * DSA verify. * * @param string $message Message. * @param string $hash_alg Hash algorithm. * @param Math_BigInteger $r r. * @param Math_BigInteger $s s. * * @return bool True if verified. */ public function verify($message, $hash_alg, $r, $s) { $hash = new Crypt_Hash($hash_alg); $hash_m = new Math_BigInteger($hash->hash($message), 256); $g = new Math_BigInteger($this->_key->key['g'], 256); $p = new Math_BigInteger($this->_key->key['p'], 256); $q = new Math_BigInteger($this->_key->key['q'], 256); $y = new Math_BigInteger($this->_key->key['y'], 256); $w = $s->modInverse($q); $hash_m_mul = $hash_m->multiply($w); $u1_base = $hash_m_mul->divide($q); $u1 = $u1_base[1]; $r_mul = $r->multiply($w); $u2_base = $r_mul->divide($q); $u2 = $u2_base[1]; $g_pow = $g->modPow($u1, $p); $y_pow = $y->modPow($u2, $p); $g_pow_mul = $g_pow->multiply($y_pow); $g_pow_mul_mod_base = $g_pow_mul->divide($p); $g_pow_mul_mod = $g_pow_mul_mod_base[1]; $v_base = $g_pow_mul_mod->divide($q); $v = $v_base[1]; return $v->compare($r) == 0; }
if ($timestampDifference < 8) { $newTimeRange = $min_timestamp - 60 * 8; $existQuery = "SELECT address,minerdiff,blockdiff,time FROM shares_history WHERE time > {$newTimeRange}"; $existResultMinersss = mysqli_query($mysqli, $existQuery) or die("Database Error"); $count_response = mysqli_num_rows($existResultMinersss); echo "\nShares_OLD_Taken:" . $count_response . ''; $current .= "\nShares_OLD_Taken:" . $count_response . ''; while ($row = mysqli_fetch_row($existResultMinersss)) { $miner_adr = $row[0]; $miner_adr_balance = new Math_BigInteger($row[1]); $totalMinersDiff = $totalMinersDiff->add($miner_adr_balance); if (!isset($miner_payouts["'{$miner_adr}'"])) { $miner_payouts["'{$miner_adr}'"] = $miner_adr_balance; $old_new_added++; } else { $miner_adr_balance_fromArray = new Math_BigInteger($miner_payouts["'{$miner_adr}'"]); $setNewValue = $miner_adr_balance_fromArray->add($miner_adr_balance); $miner_payouts["'{$miner_adr}'"] = $setNewValue->toString(); $old_old_old++; } } echo "\nShares_OLD_Taken__NEWADDED:" . $old_new_added . ''; $current .= "\nShares_OLD_Taken__NEWADDED:" . $old_new_added . ''; echo "\nShares_OLD_Taken__OLD_SUMMARY:" . $old_old_old . ''; $current .= "\nShares_OLD_Taken__OLD_SUMMARY:" . $old_old_old . ''; } echo "\n============================================================================="; echo "\nTotal Miners Diff:" . $totalMinersDiff->toString() . ' = ' . $block_coins_size->toString() . ' wei'; $current .= "\n============================================================================="; $current .= "\nTotal Miners Diff:" . $totalMinersDiff->toString() . ' = ' . $block_coins_size->toString() . ' wei'; $totalsplit = new Math_BigInteger(0);
/** * Generate a random number * * @param optional Integer $min * @param optional Integer $max * @return Math_BigInteger * @access public */ function random($min = false, $max = false) { if ($min === false) { $min = new Math_BigInteger(0); } if ($max === false) { $max = new Math_BigInteger(0x7fffffff); } $compare = $max->compare($min); if (!$compare) { return $this->_normalize($min); } else { if ($compare < 0) { // if $min is bigger then $max, swap $min and $max $temp = $max; $max = $min; $min = $temp; } } $generator = $this->generator; $max = $max->subtract($min); $max = ltrim($max->toBytes(), chr(0)); $size = strlen($max) - 1; $crypt_random = function_exists('crypt_random_string') || !class_exists('Crypt_Random') && function_exists('crypt_random_string'); if ($crypt_random) { $random = crypt_random_string($size); } else { $random = ''; if ($size & 1) { $random .= chr(mt_rand(0, 255)); } $blocks = $size >> 1; for ($i = 0; $i < $blocks; ++$i) { // mt_rand(-2147483648, 0x7FFFFFFF) always produces -2147483648 on some systems $random .= pack('n', mt_rand(0, 0xffff)); } } $fragment = new Math_BigInteger($random, 256); $leading = $fragment->compare(new Math_BigInteger(substr($max, 1), 256)) > 0 ? ord($max[0]) - 1 : ord($max[0]); if (!$crypt_random) { $msb = chr(mt_rand(0, $leading)); } else { $cutoff = floor(0xff / $leading) * $leading; while (true) { $msb = ord(crypt_random_string(1)); if ($msb <= $cutoff) { $msb %= $leading; break; } } $msb = chr($msb); } $random = new Math_BigInteger($msb . $random, 256); return $this->_normalize($random->add($min)); }
/** * RSAVP1 * * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}. * * @access private * @param Math_BigInteger $s * @return Math_BigInteger */ function _rsavp1($s) { if ($s->compare($this->zero) < 0 || $s->compare($this->modulus) > 0) { user_error('Signature representative out of range', E_USER_NOTICE); return false; } return $this->_exponentiate($s); }
/** * Get the index of a revoked certificate. * * @param array $rclist * @param String $serial * @param Boolean $create * optional * @access private * @return Integer or false */ function _revokedCertificate(&$rclist, $serial, $create = false) { $serial = new Math_BigInteger($serial); foreach ($rclist as $i => $rc) { if (!$serial->compare($rc['userCertificate'])) { return $i; } } if (!$create) { return false; } $i = count($rclist); $rclist[] = array('userCertificate' => $serial, 'revocationDate' => $this->_timeField(@date('D, d M Y H:i:s O'))); return $i; }
/** * generation of a position, logoot algorithm * @param <LogootPosition> $p is the previous logootPosition * @param <LogootPosition> $q is the next logootPosition * @param $N number of positions generated (should be 1 in our case) * @param <Integer> $rep_sid session id * @param <Integer> $rep_clock session clock * @param $boundary Cf. method * @return <LogootPosition List> $N logootPosition(s) between $start and $end */ public static function getLogootPosition(LogootPosition $p, LogootPosition $q, $nb, $rep_sid, $rep_clock = 0, $boundary = NULL) { wfDebugLog('p2p', $rep_clock . " - function LogootPosition::getLogootPosition " . $p . " / " . $q . " pour " . $nb . " position(s)"); $one = new Math_BigInteger("1"); // Recherche de l'interval optimal $index = 0; $interval = INT_MIN; $size = max($p->size(), $q->size()) + 1; $prefix_p = array(0 => array('cum_val' => "", 'id_str_val' => "")); $prefix_q = array(0 => array('cum_val' => "", 'id_str_val' => "")); while ($interval < $nb) { $index += 1; // recherche de prefix($p, index); if ($index <= $p->size()) { $str_val_p = str_pad($p->get($index - 1)->getInt(), DIGIT, "0", STR_PAD_LEFT); } else { $str_val_p = LPINTMINDIGIT; } $prefix_p[$index] = array('id_str_val' => $str_val_p, 'cum_val' => $prefix_p[$index - 1]['cum_val'] . $str_val_p); // recherche de prefix($p, index); if ($index <= $q->size()) { $str_val_q = str_pad($q->get($index - 1)->getInt(), DIGIT, "0", STR_PAD_LEFT); } else { $str_val_q = LPINTMINDIGIT; } $prefix_q[$index] = array('id_str_val' => $str_val_q, 'cum_val' => $prefix_q[$index - 1]['cum_val'] . $str_val_q); // Calcul de l'interval sur les nouveaux prefixes $BI_p = new Math_BigInteger($prefix_p[$index]['cum_val']); $BI_q = new Math_BigInteger($prefix_q[$index]['cum_val']); $BIinterval = $BI_q->subtract($BI_p)->subtract($one); $interval = (int) $BIinterval->__toString(); /*wfDebugLog('p2p', $index . " : Prefix_p " . (string) $prefix_p[$index]['cum_val'] . '/' . $prefix_p[$index]['id_str_val'] . " Prefix_q " . (string) $prefix_q[$index]['cum_val'] . '/' . $prefix_q[$index]['id_str_val'] . " Interval " . $interval);*/ } // Construction des identifiants //wfDebugLog('p2p', "N " . $nb . " Interval " . $interval . " index " . $index); $step = (int) $interval / $nb; if (isset($boundary)) { $step = $boundary < $step ? $boundary : $step; } $BI_step = new Math_BigInteger($step); $BI_r = new Math_BigInteger($prefix_p[$index]['cum_val']); $list = array(); //wfDebugLog('p2p', "Step :" . $step . "/" . $boundary); for ($j = 1; $j <= $nb; $j++) { $BI_nr = $BI_r->add(new Math_BigInteger(rand(1, $step))); //wfDebugLog('p2p', "nr " . (string) $BI_nr . " r " . (string) $BI_r); // pour découper une chaine en paquets de N car : str_split($cdc, $N) ! $str_nr0 = (string) $BI_nr; // on fait en sorte que le découpage soit un multiple de DIGIT pour ne pas créer de décallage if (strlen($str_nr0) % ($index * DIGIT) != 0) { $str_nr = str_pad($str_nr0, strlen($str_nr0) + ($index * DIGIT - strlen($str_nr0) % ($index * DIGIT)), "0", STR_PAD_LEFT); } else { $str_nr = $str_nr0; } //wfDebugLog('p2p', "str_nr0 " . $str_nr0 . " str_nr " . $str_nr); $tab_nr = str_split($str_nr, DIGIT); $pos = new LogootPosition(); for ($i = 1; $i <= count($tab_nr); $i++) { $d = $tab_nr[$i - 1]; //wfDebugLog('p2p', "$i#" . $prefix_p[$i]['id_str_val'] . "#" . $prefix_q[$i]['id_str_val'] . "#" . $d); if ($i <= $p->size() && $prefix_p[$i]['id_str_val'] == $d) { $id = new LogootId($d, $p->get($i - 1)->getSessionId(), $p->get($i - 1)->getClock()); } elseif ($i <= $q->size() && $prefix_q[$i]['id_str_val'] == $d) { $id = new LogootId($d, $q->get($i - 1)->getSessionId(), $q->get($i - 1)->getClock()); } else { $id = new LogootId($d, $rep_sid, $rep_clock); } $pos->addId($id); } wfDebugLog('p2p', "===========>" . $pos->__toString()); $list[] = $pos; $BI_r = $BI_r->add($BI_step); } return $list; }
<?php // $Id$ // Example of how to use of BigInteger. The output can be compared to the output that the BCMath functions would yield. // bcpowmod is included with Math_BigInteger.php via PHP_Compat. require __DIR__ . '/../vendor/autoload.php'; $x = mt_rand(1, 10000000); $y = mt_rand(1, 10000000); $z = mt_rand(1, 10000000); $_x = new Math_BigInteger($x); $_y = new Math_BigInteger($y); $_z = new Math_BigInteger($z); echo "\$x = {$x};\r\n"; echo "\$y = {$y};\r\n"; echo "\$z = {$z};\r\n"; echo "\r\n"; $result = bcadd($x, $y); $_result = $_x->add($_y); echo "\$result = \$x+\$y;\r\n"; echo "{$result}\r\n"; echo $_result->toString(); echo "\r\n\r\n"; $result = bcsub($result, $y); $_result = $_result->subtract($_y); echo "\$result = \$result-\$y;\r\n"; echo "{$result}\r\n"; echo $_result->toString(); echo "\r\n\r\n"; $result = bcdiv($x, $y); list($_result, ) = $_x->divide($_y); echo "\$result = \$x/\$y;\r\n";
/** * Create an 64 bit integer using bcmath or gmp * @param int $hi The higher word * @param int $lo The lower word * @return mixed The integer (as int if possible, as string if not possible) * @throws PListException if neither gmp nor bc available */ protected static function make64Int($hi, $lo) { // on x64, we can just use int if (PHP_INT_SIZE > 4) { return (int) $hi << 32 | (int) $lo; } // lower word has to be unsigned since we don't use bitwise or, we use bcadd/gmp_add $lo = sprintf("%u", $lo); // use GMP or bcmath if possible if (function_exists("gmp_mul")) { return gmp_strval(gmp_add(gmp_mul($hi, "4294967296"), $lo)); } if (function_exists("bcmul")) { return bcadd(bcmul($hi, "4294967296"), $lo); } if (class_exists('Math_BigInteger')) { $bi = new \Math_BigInteger($hi); return $bi->multiply(new \Math_BigInteger("4294967296"))->add(new \Math_BigInteger($lo))->toString(); } throw new PListException("either gmp or bc has to be installed, or the Math_BigInteger has to be available!"); }
/** * Generate a random number * * @param optional Integer $min * @param optional Integer $max * @return Math_BigInteger * @access public */ function random($min = false, $max = false) { if ($min === false) { $min = new Math_BigInteger(0); } if ($max === false) { $max = new Math_BigInteger(0x7fffffff); } $compare = $max->compare($min); if (!$compare) { return $this->_normalize($min); } else { if ($compare < 0) { // if $min is bigger then $max, swap $min and $max $temp = $max; $max = $min; $min = $temp; } } $generator = $this->generator; $max = $max->subtract($min); $max = ltrim($max->toBytes(), chr(0)); $size = strlen($max) - 1; $random = ''; $bytes = $size & 1; for ($i = 0; $i < $bytes; ++$i) { $random .= chr($generator(0, 255)); } $blocks = $size >> 1; for ($i = 0; $i < $blocks; ++$i) { // mt_rand(-2147483648, 0x7FFFFFFF) always produces -2147483648 on some systems $random .= pack('n', $generator(0, 0xffff)); } $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 $this->_normalize($random->add($min)); }
/** * Generate a random prime number. * * If there's not a prime within the given range, false will be returned. If more than $timeout seconds have elapsed, * give up and return false. * * @param optional Integer $min * @param optional Integer $max * @param optional Integer $timeout * @return Math_BigInteger * @access public * @internal See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf#page=15 HAC 4.44}. */ function randomPrime($min = false, $max = false, $timeout = false) { if ($min === false) { $min = new Math_BigInteger(0); } if ($max === false) { $max = new Math_BigInteger(0x7fffffff); } $compare = $max->compare($min); if (!$compare) { return $min->isPrime() ? $min : false; } else { if ($compare < 0) { // if $min is bigger then $max, swap $min and $max $temp = $max; $max = $min; $min = $temp; } } static $one, $two; if (!isset($one)) { $one = new Math_BigInteger(1); $two = new Math_BigInteger(2); } $start = time(); $x = $this->random($min, $max); if ($x->equals($two)) { return $x; } $x->_make_odd(); if ($x->compare($max) > 0) { // if $x > $max then $max is even and if $min == $max then no prime number exists between the specified range if ($min->equals($max)) { return false; } $x = $min->copy(); $x->_make_odd(); } $initial_x = $x->copy(); while (true) { if ($timeout !== false && time() - $start > $timeout) { return false; } if ($x->isPrime()) { return $x; } $x = $x->add($two); if ($x->compare($max) > 0) { $x = $min->copy(); if ($x->equals($two)) { return $x; } $x->_make_odd(); } if ($x->equals($initial_x)) { return false; } } }
/** * Pure-PHP implementation of SHA384 and SHA512 * * @access private * @param String $text */ function _sha512($m) { if (!class_exists('Math_BigInteger')) { require_once 'Math/BigInteger.php'; } static $init384, $init512, $k; if (!isset($k)) { // Initialize variables $init384 = array('cbbb9d5dc1059ed8', '629a292a367cd507', '9159015a3070dd17', '152fecd8f70e5939', '67332667ffc00b31', '8eb44a8768581511', 'db0c2e0d64f98fa7', '47b5481dbefa4fa4'); $init512 = array('6a09e667f3bcc908', 'bb67ae8584caa73b', '3c6ef372fe94f82b', 'a54ff53a5f1d36f1', '510e527fade682d1', '9b05688c2b3e6c1f', '1f83d9abfb41bd6b', '5be0cd19137e2179'); for ($i = 0; $i < 8; $i++) { $init384[$i] = new Math_BigInteger($init384[$i], 16); $init384[$i]->setPrecision(64); $init512[$i] = new Math_BigInteger($init512[$i], 16); $init512[$i]->setPrecision(64); } // Initialize table of round constants // (first 64 bits of the fractional parts of the cube roots of the first 80 primes 2..409) $k = array('428a2f98d728ae22', '7137449123ef65cd', 'b5c0fbcfec4d3b2f', 'e9b5dba58189dbbc', '3956c25bf348b538', '59f111f1b605d019', '923f82a4af194f9b', 'ab1c5ed5da6d8118', 'd807aa98a3030242', '12835b0145706fbe', '243185be4ee4b28c', '550c7dc3d5ffb4e2', '72be5d74f27b896f', '80deb1fe3b1696b1', '9bdc06a725c71235', 'c19bf174cf692694', 'e49b69c19ef14ad2', 'efbe4786384f25e3', '0fc19dc68b8cd5b5', '240ca1cc77ac9c65', '2de92c6f592b0275', '4a7484aa6ea6e483', '5cb0a9dcbd41fbd4', '76f988da831153b5', '983e5152ee66dfab', 'a831c66d2db43210', 'b00327c898fb213f', 'bf597fc7beef0ee4', 'c6e00bf33da88fc2', 'd5a79147930aa725', '06ca6351e003826f', '142929670a0e6e70', '27b70a8546d22ffc', '2e1b21385c26c926', '4d2c6dfc5ac42aed', '53380d139d95b3df', '650a73548baf63de', '766a0abb3c77b2a8', '81c2c92e47edaee6', '92722c851482353b', 'a2bfe8a14cf10364', 'a81a664bbc423001', 'c24b8b70d0f89791', 'c76c51a30654be30', 'd192e819d6ef5218', 'd69906245565a910', 'f40e35855771202a', '106aa07032bbd1b8', '19a4c116b8d2d0c8', '1e376c085141ab53', '2748774cdf8eeb99', '34b0bcb5e19b48a8', '391c0cb3c5c95a63', '4ed8aa4ae3418acb', '5b9cca4f7763e373', '682e6ff3d6b2b8a3', '748f82ee5defb2fc', '78a5636f43172f60', '84c87814a1f0ab72', '8cc702081a6439ec', '90befffa23631e28', 'a4506cebde82bde9', 'bef9a3f7b2c67915', 'c67178f2e372532b', 'ca273eceea26619c', 'd186b8c721c0c207', 'eada7dd6cde0eb1e', 'f57d4f7fee6ed178', '06f067aa72176fba', '0a637dc5a2c898a6', '113f9804bef90dae', '1b710b35131c471b', '28db77f523047d84', '32caab7b40c72493', '3c9ebe0a15c9bebc', '431d67c49c100d4c', '4cc5d4becb3e42b6', '597f299cfc657e2a', '5fcb6fab3ad6faec', '6c44198c4a475817'); for ($i = 0; $i < 80; $i++) { $k[$i] = new Math_BigInteger($k[$i], 16); } } $hash = $this->l == 48 ? $init384 : $init512; // Pre-processing $length = strlen($m); // to round to nearest 112 mod 128, we'll add 128 - (length + (128 - 112)) % 128 $m .= str_repeat(chr(0), 128 - ($length + 16 & 0x7f)); $m[$length] = chr(0x80); // we don't support hashing strings 512MB long $m .= pack('N4', 0, 0, 0, $length << 3); // Process the message in successive 1024-bit chunks $chunks = str_split($m, 128); foreach ($chunks as $chunk) { $w = array(); for ($i = 0; $i < 16; $i++) { $temp = new Math_BigInteger($this->_string_shift($chunk, 8), 256); $temp->setPrecision(64); $w[] = $temp; } // Extend the sixteen 32-bit words into eighty 32-bit words for ($i = 16; $i < 80; $i++) { $temp = array($w[$i - 15]->bitwise_rightRotate(1), $w[$i - 15]->bitwise_rightRotate(8), $w[$i - 15]->bitwise_rightShift(7)); $s0 = $temp[0]->bitwise_xor($temp[1]); $s0 = $s0->bitwise_xor($temp[2]); $temp = array($w[$i - 2]->bitwise_rightRotate(19), $w[$i - 2]->bitwise_rightRotate(61), $w[$i - 2]->bitwise_rightShift(6)); $s1 = $temp[0]->bitwise_xor($temp[1]); $s1 = $s1->bitwise_xor($temp[2]); $w[$i] = $w[$i - 16]->copy(); $w[$i] = $w[$i]->add($s0); $w[$i] = $w[$i]->add($w[$i - 7]); $w[$i] = $w[$i]->add($s1); } // Initialize hash value for this chunk $a = $hash[0]->copy(); $b = $hash[1]->copy(); $c = $hash[2]->copy(); $d = $hash[3]->copy(); $e = $hash[4]->copy(); $f = $hash[5]->copy(); $g = $hash[6]->copy(); $h = $hash[7]->copy(); // Main loop for ($i = 0; $i < 80; $i++) { $temp = array($a->bitwise_rightRotate(28), $a->bitwise_rightRotate(34), $a->bitwise_rightRotate(39)); $s0 = $temp[0]->bitwise_xor($temp[1]); $s0 = $s0->bitwise_xor($temp[2]); $temp = array($a->bitwise_and($b), $a->bitwise_and($c), $b->bitwise_and($c)); $maj = $temp[0]->bitwise_xor($temp[1]); $maj = $maj->bitwise_xor($temp[2]); $t2 = $s0->add($maj); $temp = array($e->bitwise_rightRotate(14), $e->bitwise_rightRotate(18), $e->bitwise_rightRotate(41)); $s1 = $temp[0]->bitwise_xor($temp[1]); $s1 = $s1->bitwise_xor($temp[2]); $temp = array($e->bitwise_and($f), $g->bitwise_and($e->bitwise_not())); $ch = $temp[0]->bitwise_xor($temp[1]); $t1 = $h->add($s1); $t1 = $t1->add($ch); $t1 = $t1->add($k[$i]); $t1 = $t1->add($w[$i]); $h = $g->copy(); $g = $f->copy(); $f = $e->copy(); $e = $d->add($t1); $d = $c->copy(); $c = $b->copy(); $b = $a->copy(); $a = $t1->add($t2); } // Add this chunk's hash to result so far $hash = array($hash[0]->add($a), $hash[1]->add($b), $hash[2]->add($c), $hash[3]->add($d), $hash[4]->add($e), $hash[5]->add($f), $hash[6]->add($g), $hash[7]->add($h)); } // Produce the final hash value (big-endian) // (Crypt_Hash::hash() trims the output for hashes but not for HMACs. as such, we trim the output here) $temp = $hash[0]->toBytes() . $hash[1]->toBytes() . $hash[2]->toBytes() . $hash[3]->toBytes() . $hash[4]->toBytes() . $hash[5]->toBytes(); if ($this->l != 48) { $temp .= $hash[6]->toBytes() . $hash[7]->toBytes(); } return $temp; }
/** * Default Constructor. * * Connects to an SSHv1 server * * @param String $host * @param optional Integer $port * @param optional Integer $timeout * @param optional Integer $cipher * @return Net_SSH1 * @access public */ function Net_SSH1($host, $port = 22, $timeout = 10, $cipher = NET_SSH1_CIPHER_3DES) { $this->fsock = @fsockopen($host, $port, $errno, $errstr, $timeout); 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_3CBC); $this->crypto->disablePadding(); $this->crypto->enableContinuousBuffer(); $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; }
/** * Returns the server public host key. * * Caching this the first time you connect to a server and checking the result on subsequent connections * is recommended. Returns false if the server signature is not signed correctly with the public host key. * * @return Mixed * @access public */ function getServerPublicHostKey() { if (!($this->bitmap & NET_SSH2_MASK_CONSTRUCTOR)) { $this->bitmap |= NET_SSH2_MASK_CONSTRUCTOR; if (!$this->_connect()) { return false; } } $signature = $this->signature; $server_public_host_key = $this->server_public_host_key; extract(unpack('Nlength', $this->_string_shift($server_public_host_key, 4))); $this->_string_shift($server_public_host_key, $length); if ($this->signature_validated) { return $this->bitmap ? $this->signature_format . ' ' . base64_encode($this->server_public_host_key) : false; } $this->signature_validated = true; switch ($this->signature_format) { case 'ssh-dss': $zero = new Math_BigInteger(); $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $p = new Math_BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $q = new Math_BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $g = new Math_BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $y = new Math_BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); /* The value for 'dss_signature_blob' is encoded as a string containing r, followed by s (which are 160-bit integers, without lengths or padding, unsigned, and in network byte order). */ $temp = unpack('Nlength', $this->_string_shift($signature, 4)); if ($temp['length'] != 40) { user_error('Invalid signature'); return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); } $r = new Math_BigInteger($this->_string_shift($signature, 20), 256); $s = new Math_BigInteger($this->_string_shift($signature, 20), 256); switch (true) { case $r->equals($zero): case $r->compare($q) >= 0: case $s->equals($zero): case $s->compare($q) >= 0: user_error('Invalid signature'); return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); } $w = $s->modInverse($q); $u1 = $w->multiply(new Math_BigInteger(sha1($this->exchange_hash), 16)); list(, $u1) = $u1->divide($q); $u2 = $w->multiply($r); list(, $u2) = $u2->divide($q); $g = $g->modPow($u1, $p); $y = $y->modPow($u2, $p); $v = $g->multiply($y); list(, $v) = $v->divide($p); list(, $v) = $v->divide($q); if (!$v->equals($r)) { user_error('Bad server signature'); return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE); } break; case 'ssh-rsa': $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $e = new Math_BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $n = new Math_BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); $nLength = $temp['length']; /* $temp = unpack('Nlength', $this->_string_shift($signature, 4)); $signature = $this->_string_shift($signature, $temp['length']); if (!class_exists('Crypt_RSA')) { include_once 'Crypt/RSA.php'; } $rsa = new Crypt_RSA(); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $rsa->loadKey(array('e' => $e, 'n' => $n), CRYPT_RSA_PUBLIC_FORMAT_RAW); if (!$rsa->verify($this->exchange_hash, $signature)) { user_error('Bad server signature'); return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE); } */ $temp = unpack('Nlength', $this->_string_shift($signature, 4)); $s = new Math_BigInteger($this->_string_shift($signature, $temp['length']), 256); // validate an RSA signature per "8.2 RSASSA-PKCS1-v1_5", "5.2.2 RSAVP1", and "9.1 EMSA-PSS" in the // following URL: // ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1.pdf // also, see SSHRSA.c (rsa2_verifysig) in PuTTy's source. if ($s->compare(new Math_BigInteger()) < 0 || $s->compare($n->subtract(new Math_BigInteger(1))) > 0) { user_error('Invalid signature'); return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); } $s = $s->modPow($e, $n); $s = $s->toBytes(); $h = pack('N4H*', 0x302130, 0x906052b, 0xe03021a, 0x5000414, sha1($this->exchange_hash)); $h = chr(0x1) . str_repeat(chr(0xff), $nLength - 3 - strlen($h)) . $h; if ($s != $h) { user_error('Bad server signature'); return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE); } break; default: user_error('Unsupported signature format'); return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE); } return $this->signature_format . ' ' . base64_encode($this->server_public_host_key); }
if ($hash_rate) { $shareCheckerKey = 'submiting_' . $payout_addr . '_' . $hash_rate; //DONE HIGHER - //$CheckShareData = $m->get($shareCheckerKey); if (!$CheckShareData) { $fixed_diff = floatval($hash_rate); } else { $fixed_diff = floatval($hash_rate * $CheckShareData * 4); } $fixed_diff = $fixed_diff * $miner_diff; $fixed_diff = new Math_BigInteger($fixed_diff); $current .= "\nFixed diff value:" . $fixed_diff; } else { die('You need to specify your hashrate!'); } $a256 = new Math_BigInteger('115792089237316195423570985008687907853269984665640564039457584007913129639936'); //2^256 //Convert diff decimal to hex 256bit $new_block_diff = new Math_BigInteger($fixed_diff); list($quotient, $remainder) = $a256->divide($new_block_diff); $target_diff = $quotient->toString(); $target_diff = bcdechex($target_diff); $currentLenght = strlen($target_diff); $desiredLenght = 64; if ($currentLenght < $desiredLenght) { $toadd = $desiredLenght - $currentLenght; for ($i = 0; $i < $toadd; $i++) { $fix .= '0'; } $target_diff = '0x' . $fix . $target_diff; }
/** * Default Constructor. * * Connects to an SSHv1 server * * @param String $host * @param optional Integer $port * @param optional Integer $timeout * @param optional Integer $cipher * @return Net_SSH1 * @access public */ function Net_SSH1($host, $port = 22, $timeout = 10, $cipher = NET_SSH1_CIPHER_3DES) { if (!class_exists('Math_BigInteger')) { include_once EASYWIDIR . '/third_party/phpseclib/Math/BigInteger.php'; } // Include Crypt_Random // the class_exists() will only be called if the crypt_random_string function hasn't been defined and // will trigger a call to __autoload() if you're wanting to auto-load classes // call function_exists() a second time to stop the include_once from being called outside // of the auto loader if (!function_exists('crypt_random_string') && !class_exists('Crypt_Random') && !function_exists('crypt_random_string')) { include_once EASYWIDIR . '/third_party/phpseclib/Crypt/Random.php'; } $this->protocol_flags = array(1 => 'NET_SSH1_MSG_DISCONNECT', 2 => 'NET_SSH1_SMSG_PUBLIC_KEY', 3 => 'NET_SSH1_CMSG_SESSION_KEY', 4 => 'NET_SSH1_CMSG_USER', 9 => 'NET_SSH1_CMSG_AUTH_PASSWORD', 10 => 'NET_SSH1_CMSG_REQUEST_PTY', 12 => 'NET_SSH1_CMSG_EXEC_SHELL', 13 => 'NET_SSH1_CMSG_EXEC_CMD', 14 => 'NET_SSH1_SMSG_SUCCESS', 15 => 'NET_SSH1_SMSG_FAILURE', 16 => 'NET_SSH1_CMSG_STDIN_DATA', 17 => 'NET_SSH1_SMSG_STDOUT_DATA', 18 => 'NET_SSH1_SMSG_STDERR_DATA', 19 => 'NET_SSH1_CMSG_EOF', 20 => 'NET_SSH1_SMSG_EXITSTATUS', 33 => 'NET_SSH1_CMSG_EXIT_CONFIRMATION'); $this->_define_array($this->protocol_flags); $this->fsock = @fsockopen($host, $port, $errno, $errstr, $timeout); if (!$this->fsock) { user_error(rtrim("Cannot connect to {$host}. Error {$errno}. {$errstr}")); return; } $this->server_identification = $init_line = fgets($this->fsock, 255); if (defined('NET_SSH1_LOGGING')) { $this->_append_log('<-', $this->server_identification); $this->_append_log('->', $this->identifier . "\r\n"); } if (!preg_match('#SSH-([0-9\\.]+)-(.+)#', $init_line, $parts)) { user_error('Can only connect to SSH servers'); return; } if ($parts[1][0] != 1) { user_error("Cannot connect to SSH {$parts['1']} servers"); 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'); 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 extract(unpack('Nsupported_ciphers_mask', $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 extract(unpack('Nsupported_authentications_mask', $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 = crypt_random_string(32); $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'); return; } switch ($cipher) { //case NET_SSH1_CIPHER_NONE: // $this->crypto = new Crypt_Null(); // break; case NET_SSH1_CIPHER_DES: if (!class_exists('Crypt_DES')) { include_once EASYWIDIR . '/third_party/phpseclib/Crypt/DES.php'; } $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: if (!class_exists('Crypt_TripleDES')) { include_once EASYWIDIR . '/third_party/phpseclib/Crypt/TripleDES.php'; } $this->crypto = new Crypt_TripleDES(CRYPT_DES_MODE_3CBC); $this->crypto->disablePadding(); $this->crypto->enableContinuousBuffer(); $this->crypto->setKey(substr($session_key, 0, 24)); break; //case NET_SSH1_CIPHER_RC4: // if (!class_exists('Crypt_RC4')) { // include_once('Crypt/RC4.php'); // } // $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'); return; } $this->bitmap = NET_SSH1_MASK_CONSTRUCTOR; }
} echo "\n\n" . sprintf('%f', $weisummary) . ' wei'; $current .= "\n\n" . sprintf('%f', $weisummary) . ' wei'; echo "\n\n" . sprintf('%f', $withdrawcount) . ' withdraw Count'; $current .= "\n\n" . sprintf('%f', $withdrawcount) . ' withdraw Count'; $data = array("jsonrpc" => "2.0", "method" => "eth_getBalance", "params" => [$coinbase, 'latest'], "id" => 1); $data_string = json_encode($data); $ch1 = curl_init('http://127.0.0.1:8983'); curl_setopt($ch1, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch1, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch1, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string))); $result3 = curl_exec($ch1); $block_info_last = json_decode($result3, true); $escapeDot = explode('.', sprintf('%f', hexdec($block_info_last['result']))); $balanceaddr = new Math_BigInteger($escapeDot[0]); $updatebalanceaddr = $balanceaddr->toString(); $task = "UPDATE info SET balance='{$updatebalanceaddr}' WHERE id=1;"; $query = mysqli_query($mysqli, $task) or die("Database Error"); file_put_contents($file, $current); $m->set('state_work', 0); function bcdechex($dec) { $hex = ''; do { $last = bcmod($dec, 16); $hex = dechex($last) . $hex; $dec = bcdiv(bcsub($dec, $last), 16); } while ($dec > 0); return $hex; }
/** * Connect to an SSHv1 server * * @return Boolean * @access private */ function _connect() { $this->fsock = @fsockopen($this->host, $this->port, $errno, $errstr, $this->connectionTimeout); if (!$this->fsock) { user_error(rtrim("Cannot connect to {$this->host}:{$this->port}. Error {$errno}. {$errstr}")); return false; } $this->server_identification = $init_line = fgets($this->fsock, 255); if (defined('NET_SSH1_LOGGING')) { $this->_append_log('<-', $this->server_identification); $this->_append_log('->', $this->identifier . "\r\n"); } if (!preg_match('#SSH-([0-9\\.]+)-(.+)#', $init_line, $parts)) { user_error('Can only connect to SSH servers'); return false; } if ($parts[1][0] != 1) { user_error("Cannot connect to SSH {$parts['1']} servers"); return false; } 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'); return false; } $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 extract(unpack('Nsupported_ciphers_mask', $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 extract(unpack('Nsupported_authentications_mask', $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 = crypt_random_string(32); $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[$this->cipher]) ? $this->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'); return false; } switch ($cipher) { //case NET_SSH1_CIPHER_NONE: // $this->crypto = new Crypt_Null(); // break; case NET_SSH1_CIPHER_DES: if (!class_exists('Crypt_DES')) { include_once 'Crypt/DES.php'; } $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: if (!class_exists('Crypt_TripleDES')) { include_once 'Crypt/TripleDES.php'; } $this->crypto = new Crypt_TripleDES(CRYPT_DES_MODE_3CBC); $this->crypto->disablePadding(); $this->crypto->enableContinuousBuffer(); $this->crypto->setKey(substr($session_key, 0, 24)); break; //case NET_SSH1_CIPHER_RC4: // if (!class_exists('Crypt_RC4')) { // include_once 'Crypt/RC4.php'; // } // $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'); return false; } $this->bitmap = NET_SSH1_MASK_CONNECTED; return true; }
/** * Get the index of a revoked certificate. * * @param array $rclist * @param String $serial * @param Boolean $create optional * @access private * @return Integer or false */ function _revokedCertificate(&$rclist, $serial, $create = false) { $serial = new Math_BigInteger($serial); foreach ($rclist as $i => $rc) { if (!$serial->compare($rc['userCertificate'])) { return $i; } } if (!$create) { return false; } $i = count($rclist); $rclist[] = array('userCertificate' => $serial, 'revocationDate' => array('generalTime' => @date('M j H:i:s Y T'))); return $i; }
/** * Generate a random prime number. * * If there's not a prime within the given range, false will be returned. * If more than $timeout seconds have elapsed, give up and return false. * * @param Math_BigInteger $arg1 * @param Math_BigInteger $arg2 * @param int $timeout * @return Math_BigInteger|false * @access public * @internal See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf#page=15 HAC 4.44}. */ function randomPrime($arg1, $arg2 = false, $timeout = false) { if ($arg1 === false) { return false; } if ($arg2 === false) { $max = $arg1; $min = $this; } else { $min = $arg1; $max = $arg2; } $compare = $max->compare($min); if (!$compare) { return $min->isPrime() ? $min : false; } elseif ($compare < 0) { // if $min is bigger then $max, swap $min and $max $temp = $max; $max = $min; $min = $temp; } static $one, $two; if (!isset($one)) { $one = new Math_BigInteger(1); $two = new Math_BigInteger(2); } $start = time(); $x = $this->random($min, $max); // gmp_nextprime() requires PHP 5 >= 5.2.0 per <http://php.net/gmp-nextprime>. if (MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_GMP && extension_loaded('gmp') && version_compare(PHP_VERSION, '5.2.0', '>=')) { $p = new Math_BigInteger(); $p->value = gmp_nextprime($x->value); if ($p->compare($max) <= 0) { return $p; } if (!$min->equals($x)) { $x = $x->subtract($one); } return $x->randomPrime($min, $x); } if ($x->equals($two)) { return $x; } $x->_make_odd(); if ($x->compare($max) > 0) { // if $x > $max then $max is even and if $min == $max then no prime number exists between the specified range if ($min->equals($max)) { return false; } $x = $min->copy(); $x->_make_odd(); } $initial_x = $x->copy(); while (true) { if ($timeout !== false && time() - $start > $timeout) { return false; } if ($x->isPrime()) { return $x; } $x = $x->add($two); if ($x->compare($max) > 0) { $x = $min->copy(); if ($x->equals($two)) { return $x; } $x->_make_odd(); } if ($x->equals($initial_x)) { return false; } } }
<?php require "rsa.php"; require "BigInteger.php"; $text = "hi man"; $public = 65537; $modulus = "D192471B8699640F931FE6F4FACC3E990B894F894CEA5BEE0DCBD7A4B76752F7345CF9B5F1271001B724F7A0ABF0A6E911E309536F4BE4749E92DCC531B8E36B95969D206649C9DD2371B413A8DFD9B92569660B1499A5CD310B86A8FDE24988E456897A416D2E7B0B649F0714F322C57EF92563B21A448D1072FF3806C34C75"; $keylength = 1024; $modulus_16 = new Math_BigInteger($modulus, 16); $mend = $modulus_16->toString(); echo "now we are going to eccrypt ' {$text} '\n"; $encrypted = rsa_encrypt($text, $public, $mend, $keylength); echo bin2hex($encrypted); echo "\n"; echo "now wo are going to decrypt it"; $decrypted = rsa_decrypt();