public function testBaseConvertDigits() { $converter = new BaseConvertConverter(new Base62Symbols()); $this->assertSame(explode(':', '4:16:12:8:33:15:15:6:34:11:20:0:20:28:32:4:24:0:32:4:12:16:12:28:32'), $converter->convert(gmp_strval(gmp_pow(10, 38), 10), 10, 36)); $this->assertSame(str_split('100000000000', 1), $converter->convert('100000000000', 10, 10)); $this->assertSame(explode(':', '3:18:2:10:0:0:0:0:0'), $converter->convert('100000000000', 10, 20)); }
/** * Exponential expression / raise number into power * * @param string $base base to raise * @param string $exp exponent to use * @param mixed $use_function pow function to use, or false for auto-detect * * @return mixed string or float */ function PMA_pow($base, $exp, $use_function = false) { static $pow_function = null; if (null == $pow_function) { $pow_function = PMA_detect_pow(); } if (!$use_function) { $use_function = $pow_function; } if ($exp < 0 && 'pow' != $use_function) { return false; } switch ($use_function) { case 'bcpow': // bcscale() needed for testing PMA_pow() with base values < 1 bcscale(10); $pow = bcpow($base, $exp); break; case 'gmp_pow': $pow = gmp_strval(gmp_pow($base, $exp)); break; case 'pow': $base = (double) $base; $exp = (int) $exp; $pow = pow($base, $exp); break; default: $pow = $use_function($base, $exp); } return $pow; }
protected function assetNameToIDHex($asset_name) { if ($asset_name == 'BTC') { return '0'; } if ($asset_name == 'XCP') { return '1'; } if (substr($asset_name, 0, 1) == 'A') { // numerical asset // An integer between 26^12 + 1 and 256^8 (inclusive) $asset_id = gmp_init(substr($asset_name, 1)); if ($asset_id < gmp_init(26) ** 12 + 1) { throw new Exception("Asset ID was too low", 1); } if ($asset_id > gmp_init(2) ** 64 - 1) { throw new Exception("Asset ID was too high", 1); } return gmp_strval($asset_id, 16); } $n = gmp_init(0); for ($i = 0; $i < strlen($asset_name); $i++) { $n = gmp_mul($n, 26); $char = ord(substr($asset_name, $i, 1)); if ($char < 65 or $char > 90) { throw new Exception("Asset name invalid", 1); } $digit = $char - 65; $n = gmp_add($n, $digit); } return gmp_strval($n, 16); }
public function testGMP() { $math = \Mdanter\Ecc\EccFactory::getAdapter(); $I_l = "e97a4d6be13f8f5804c0a76080428fc6d51260f74801678c4127045d2640af14"; $private_key = "142018c66b43a95de58c1cf603446fc0da322bc15fb4df068b844b57c706dd05"; $n = "115792089237316195423570985008687907852837564279074904382605163141518161494337"; $gmp_I_l = gmp_init($I_l, 16); $gmp_private_key = gmp_init($private_key, 16); $gmp_add = gmp_add($gmp_I_l, $gmp_private_key); $gmp_add_res = gmp_strval($gmp_add, 10); $this->assertEquals("105604983404708440304568772161069255144976878830542744455590282065741265022740", gmp_strval($gmp_I_l)); $this->assertEquals("9102967069016248707169900673545386030247334423973996501079368232055584775429", gmp_strval($gmp_private_key)); $this->assertEquals("114707950473724689011738672834614641175224213254516740956669650297796849798169", gmp_strval($gmp_add)); $this->assertEquals("114707950473724689011738672834614641175224213254516740956669650297796849798169", gmp_strval(gmp_div_r($gmp_add, gmp_init($n)))); $this->assertEquals("-4", gmp_strval(gmp_cmp(0, gmp_div_r($gmp_add, $n)))); $this->assertEquals("230500039711040884435309657843302549028061777533591645339274813439315011292506", gmp_strval(gmp_add(gmp_init($n), gmp_div_r($gmp_add, gmp_init($n))))); $gmp_mod2 = $math->mod($gmp_add_res, $n); $this->assertTrue(is_string($gmp_mod2)); $this->assertEquals("114707950473724689011738672834614641175224213254516740956669650297796849798169", $gmp_mod2); $this->assertEquals("114707950473724689011738672834614641175224213254516740956669650297796849798169", $gmp_mod2); // when no base is provided both a resource and string work $this->assertEquals("114707950473724689011738672834614641175224213254516740956669650297796849798169", gmp_strval(gmp_init($gmp_mod2))); $this->assertEquals("114707950473724689011738672834614641175224213254516740956669650297796849798169", gmp_strval($gmp_mod2)); // when base is provided it fails on HHVM when inputting a string $this->assertEquals("fd9a66324c8338b5ea4cc4568386ff87af448cb8a7b64692ccab4fb4ed478c19", gmp_strval(gmp_init($gmp_mod2), 16)); // $this->assertEquals("fd9a66324c8338b5ea4cc4568386ff87af448cb8a7b64692ccab4fb4ed478c19", gmp_strval($gmp_mod2, 16)); $this->assertEquals("fd9a66324c8338b5ea4cc4568386ff87af448cb8a7b64692ccab4fb4ed478c19", str_pad(gmp_strval(gmp_init($gmp_mod2), 16), 64, '0', STR_PAD_LEFT)); }
public static function generate($ver = 4, $node = null, $clockSeq = null, $ns = null, $name = null) { $uuid = null; /* Create a new UUID based on provided data. */ switch ((int) $ver) { case 1: $uuid = Uuid::uuid1($node, $clockSeq); break; case 2: // Version 2 is not supported throw new \RuntimeException('UUID version 2 is unsupported.'); case 3: $uuid = Uuid::uuid3($ns, $name); break; case 4: $uuid = Uuid::uuid4(); break; case 5: $uuid = Uuid::uuid5($ns, $name); break; default: throw new \RuntimeException('Selected UUID version is invalid or unsupported.'); } if (function_exists('gmp_strval')) { return gmp_strval(gmp_init($uuid->getHex(), 16), 62); } return Base62::encode((string) $uuid->getInteger()); }
/** * _baseConvert * * Convert values from base-A to base-B with GMP-functions * * @param string $value Input value for convert * @param int $from From base-A value * @param int $to To base-B value * @return string Result string */ private static function _baseConvert($value, $from, $to) { if (!function_exists('gmp_init')) { throw new \SystemErrorException(array('title' => 'HashHelper error', 'description' => 'Requires the PHP gmp module')); } return gmp_strval(gmp_init($value, $from), $to); }
/** * Convert 32-bit SteamID to 64-bit SteamID * * @param string|int $userId * * @return string * @throws Exception */ public static function to64Bit($userId) { if (!function_exists('gmp_add')) { throw new Exception("GMP Library not installed. Cannot convert SteamIDs."); } return gmp_strval(gmp_add(gmp_mul(sprintf("%u", bindec(self::STEAM_ID_UPPER_BITS)), "4294967296"), sprintf("%u", $userId))); }
function g($val = null) { if (is_string($val)) { $this->g = gmp_init($val, 16); } return gmp_strval($this->g, 16); }
function Zend_OpenId_bigNumToBin($bn) { if (extension_loaded('gmp')) { $s = gmp_strval($bn, 16); if (strlen($s) % 2 != 0) { $s = '0' . $s; } return pack("H*", $s); } else { if (extension_loaded('bcmath')) { $cmp = bccomp($bn, 0); if ($cmp == 0) { return chr(0); } else { if ($cmp < 0) { throw new Zend_OpenId_Exception('Big integer arithmetic error', Zend_OpenId_Exception::ERROR_LONG_MATH); } } $bin = ""; while (bccomp($bn, 0) > 0) { $bin = chr(bcmod($bn, 256)) . $bin; $bn = bcdiv($bn, 256); } return $bin; } } throw new Zend_OpenId_Exception('The system doesn\'t have proper big integer extension', Zend_OpenId_Exception::UNSUPPORTED_LONG_MATH); }
/** * 与えられた値を整数型に変換して返します。 * @link http://www.hcn.zaq.ne.jp/___/WEB/WebIDL-ja.html#es-integers Web IDL (第2版 — 日本語訳) * @param boolean|integer|float|string|resource|\GMP|\SplInt $value * @param string $type byte、octet、short、unsigned short、long、unsigned long、long long、unsigned long long * @param integer|float $min 浮動小数点型で正確に扱える整数の範囲よりも、整数型で扱える整数の範囲が狭ければ (整数型が32bitである環境なら) 浮動小数点数。 * @param integer|float $max 浮動小数点型で正確に扱える整数の範囲よりも、整数型で扱える整数の範囲が狭ければ (整数型が32bitである環境なら) 浮動小数点数。 * @param integer $bits * @param booelan $signed * @param string $extendedAttribute 拡張属性。[EnforceRange] か [Clamp] のいずれか。 * @return integer|float 整数型の範囲を超える場合は浮動小数点数。 * @throws \InvalidArgumentException 配列、NULL が与えられた場合。または、GMP、SplInt 以外のオブジェクトが与えられた場合。 * @throws \DomainException $extendedAttribute が [EnforceRange]、かつ与えられたの値が $min 〜 $max に収まらなかった場合。 */ private static function toInteger($value, $type, $min, $max, $bits, $signed, $extendedAttribute = null) { /** @var string 要求される型。 */ $expectedType = sprintf('%s (an integer in the range of %s to %s)', $type, is_float($min) ? number_format($min, 0, '', '') : $min, is_float($max) ? number_format($max, 0, '', '') : $max); if (!self::isIntegerCastable($value)) { throw new \InvalidArgumentException(ErrorMessageCreator::create($value, $expectedType)); } if ($value instanceof \GMP || is_resource($value) && get_resource_type($value) === 'GMP integer') { // GMP数であれば、あらかじめ文字列に変換しておく $value = gmp_strval($value); } /** @var integer|float 与えられた値の数値表現。整数型の範囲を超える場合は浮動小数点数。整数値となる場合、小数部があれば0方向へ丸められる。 */ $number = is_float($value) || (double) $value < self::$phpIntMin || (double) $value > PHP_INT_MAX ? (double) $value : (int) $value; if ($extendedAttribute === '[EnforceRange]') { /** @var integer|float 与えられた値の整数表現。整数型の範囲を超える場合は浮動小数点数。 */ $integer = self::roundTowardZero($number); if (!is_finite($number) || $integer < $min || $integer > $max) { throw new \DomainException(ErrorMessageCreator::create($value, $expectedType)); } } elseif (!is_nan($number) && $extendedAttribute === '[Clamp]') { $number = min(max($number, $min), $max); $integer = is_float($number) ? round($number, 0, PHP_ROUND_HALF_EVEN) : $number; } elseif (!is_finite($number)) { $integer = 0; } else { $integer = self::modulo(self::roundTowardZero($number), pow(2, $bits)); if ($signed && $integer >= pow(2, $bits - 1)) { $integer -= pow(2, $bits); } } return is_float($integer) && $integer >= self::$phpIntMin && $integer <= PHP_INT_MAX ? (int) $integer : $integer; }
function powmod($base, $exponent, $modulus) { if (function_exists('gmp_powm')) { // fast return gmp_strval(gmp_powm($base, $exponent, $modulus)); } if (function_exists('bi_powmod')) { // not tested return bi_sto_str(bi_powmod($base, $exponent, $modulus)); } if (function_exists('bcpowmod')) { // slow return bcpowmod($base, $exponent, $modulus); } // emulation, slow $square = bcmod($base, $modulus); $result = 1; while (bccomp($exponent, 0) > 0) { if (bcmod($exponent, 2)) { $result = bcmod(bcmul($result, $square), $modulus); } $square = bcmod(bcmul($square, $square), $modulus); $exponent = bcdiv($exponent, 2); } return $result; }
public static function num2str($num) { switch (BigInt::support()) { case 'gmp': $str = gmp_strval($num, 16); $len = strlen($str); if ($len % 2 == 1) { $str = '0' . $str; } return pack("H*", $str); case 'big_int': $str = bi_to_str($num, 16); $len = strlen($str); if ($len % 2 == 1) { $str = '0' . $str; } return pack("H*", $str); case 'bcmath': bcscale(0); $str = ""; while (bccomp($num, '0') == 1) { $str = chr(bcmod($num, '256')) . $str; $num = bcdiv($num, '256'); } return $str; case '': default: return BigInt::_num2str($num); } }
function internal_to_numstr($num, $precision = -1, $round = true) { if ($precision == -1) { $precision = 8; $tidy = true; } else { $tidy = false; } if (!is_string($num) && !is_resource($num)) { throw new Error('Coding error!', "internal_to_numstr argument has type '" . gettype($num) . "'"); } $repr = gmp_strval($num); if ($round) { if ($repr > 0) { $repr = bcadd($repr, pow(10, 8 - $precision) / 2); } else { $repr = bcsub($repr, pow(10, 8 - $precision) / 2); } } $repr = bcdiv($repr, pow(10, 8), $precision); // now tidy output... if ($tidy) { return clean_sql_numstr($repr); } return sprintf("%.{$precision}f", $repr); }
/** * Exponential expression / raise number into power * * @param string $base base to raise * @param string $exp exponent to use * @param string $use_function pow function to use, or false for auto-detect * * @return mixed string or float */ public static function pow($base, $exp, $use_function = '') { static $pow_function = null; if ($pow_function == null) { $pow_function = self::detectPow(); } if (!$use_function) { if ($exp < 0) { $use_function = 'pow'; } else { $use_function = $pow_function; } } if ($exp < 0 && $use_function != 'pow') { return false; } switch ($use_function) { case 'bcpow': // bcscale() needed for testing pow() with base values < 1 bcscale(10); $pow = bcpow($base, $exp); break; case 'gmp_pow': $pow = gmp_strval(gmp_pow($base, $exp)); break; case 'pow': $base = (double) $base; $exp = (int) $exp; $pow = pow($base, $exp); break; default: $pow = $use_function($base, $exp); } return $pow; }
/** * @param int $cycle weather cycle we in (hours/3) * @param CWeatherFunction $wf cycle season weather function (weights) * * @return WeatherValue */ public function getCycleWeatherValue($cycle, CWeatherFunction $wf) { $numWS = $wf->getNumWeatherSetups(); if (!$numWS) { return 0; } /* old weather $noiseValue = $this->rawWeatherProvider($cycle); // sum all weights, usually adds up to 100 $value = (int)($noiseValue * $wf->getWeatherSetupsTotalWeight()); */ $noiseValue = \Nel\Misc\wang_hash64($cycle); // noise is 64bit unsigned, so use GMP library // value = wangHash64(cycle) % wf.getWeatherSetupsTotalWeight(); $value = gmp_strval(gmp_mod($noiseValue, $wf->getWeatherSetupsTotalWeight())); $currWeight = 0; for ($k = 0; $k < $numWS; $k++) { $weight = $wf->getWeatherSetupWeight($k); if ($value >= $currWeight && $value < $currWeight + $weight) { $scaledWeather = ($value - $currWeight) / $weight + $k; $weather = $scaledWeather / $numWS; return new WeatherValue($k, $weather, $wf); } $currWeight += $weight; } return new WeatherValue($numWS, 1, $wf); }
function pidigits($N) { $k = 1; $n1 = gmp_init(4); $n2 = gmp_init(3); $d = gmp_init(1); $i = 0; while ($i < $N) { $y = digit($n1, $n2, $d); if ($y !== false) { echo gmp_strval($y); $i++; if ($i % 10 == 0) { echo "\t:", $i, "\n"; } extractd($n1, $n2, $d, $y); } else { produce($n1, $n2, $d, $k); $k++; } } if ($i % 10 != 0) { echo str_repeat(' ', 10 - $N % 10), "\t:", $N, "\n"; } }
function GetAuthID($i64friendID) { $tmpfriendID = $i64friendID; $iServer = "1"; if (extension_loaded('bcmath') == 1) { //decode communityid with bcmath if (bcmod($i64friendID, "2") == "0") { $iServer = "0"; } $tmpfriendID = bcsub($tmpfriendID, $iServer); if (bccomp("76561197960265728", $tmpfriendID) == -1) { $tmpfriendID = bcsub($tmpfriendID, "76561197960265728"); } $tmpfriendID = bcdiv($tmpfriendID, "2"); return "STEAM_0:" . $iServer . ":" . $tmpfriendID; } else { if (extension_loaded('gmp') == 1) { //decode communityid with gmp if (gmp_mod($i64friendID, "2") == "0") { $iServer = "0"; } $tmpfriendID = gmp_sub($tmpfriendID, $iServer); if (gmp_cmp("76561197960265728", $tmpfriendID) == -1) { $tmpfriendID = gmp_sub($tmpfriendID, "76561197960265728"); } $tmpfriendID = gmp_div($tmpfriendID, "2"); return "STEAM_0:" . $iServer . ":" . gmp_strval($tmpfriendID); } } return false; }
/** * Pack a long. * * If it is a 32bit PHP we suppose that this log is treated by bcmath * TODO 32bit * * @param int|string $value * * @return string the packed long */ public static function packLong($value) { if (PHP_INT_SIZE > 4) { $value = (int) $value; $binaryString = chr($value >> 56 & 0xff) . chr($value >> 48 & 0xff) . chr($value >> 40 & 0xff) . chr($value >> 32 & 0xff) . chr($value >> 24 & 0xff) . chr($value >> 16 & 0xff) . chr($value >> 8 & 0xff) . chr($value & 0xff); } else { /* * To get the two's complement of a binary number, * the bits are inverted, or "flipped", * by using the bitwise NOT operation; * the value of 1 is then added to the resulting value */ $bitString = ''; $isNegative = $value[0] == '-'; if (function_exists("bcmod")) { //add 1 for the two's complement if ($isNegative) { $value = bcadd($value, '1'); } while ($value !== '0') { $bitString = (string) abs((int) bcmod($value, '2')) . $bitString; $value = bcdiv($value, '2'); } } elseif (function_exists("gmp_mod")) { //add 1 for the two's complement if ($isNegative) { $value = gmp_strval(gmp_add($value, '1')); } while ($value !== '0') { $bitString = gmp_strval(gmp_abs(gmp_mod($value, '2'))) . $bitString; $value = gmp_strval(gmp_div_q($value, '2')); } } else { while ($value != 0) { list($value, $remainder) = self::str2bin((string) $value); $bitString = $remainder . $bitString; } } //Now do the logical not for the two's complement last phase if ($isNegative) { $len = strlen($bitString); for ($x = 0; $x < $len; $x++) { $bitString[$x] = $bitString[$x] == '1' ? '0' : '1'; } } //pad to have 64 bit if ($bitString != '' && $isNegative) { $bitString = str_pad($bitString, 64, '1', STR_PAD_LEFT); } else { $bitString = str_pad($bitString, 64, '0', STR_PAD_LEFT); } $hi = substr($bitString, 0, 32); $lo = substr($bitString, 32, 32); $hiBin = pack('H*', str_pad(base_convert($hi, 2, 16), 8, 0, STR_PAD_LEFT)); $loBin = pack('H*', str_pad(base_convert($lo, 2, 16), 8, 0, STR_PAD_LEFT)); $binaryString = $hiBin . $loBin; } return $binaryString; }
public static function combinations($num, $repetitions) { if ($num >= $repetitions) { return gmp_strval(gmp_fact($num)) / (gmp_strval(gmp_fact($repetitions)) * gmp_strval(gmp_fact($num - $repetitions))); } else { exit('Error you could, not second parameter that is greater than the first one.'); } }
protected function setIpAttribute($key, $value) { if (!is_null($value)) { $value = gmp_strval(gmp_import(inet_pton($value))); } $this->attributes[$key] = $value; return $this; }
/** * @dataProvider encryptedWords */ public function testEncrypt($in, $out) { $primeNumber = Math\Calculator::generateNthPrime(10000); $fibonacciSum = Math\Calculator::sumOfFibonacciElements(49); $tmp = gmp_strval(gmp_add($primeNumber, $fibonacciSum)); $key = intval(strrev(substr($tmp, 5, -4))); $this->assertEquals($out, self::$cipher->encrypt($in, $key)); }
function gmp_shiftr($x, $n) { if ($x < 0) { return gmp_strval(gmp_com(gmp_div(gmp_com($x), gmp_pow(2, $n)))); } else { return gmp_strval(gmp_div($x, gmp_pow(2, $n))); } }
/** * @return string */ public final function getSerialNumber() { $String = $this->getIdentifier(); $String = strlen($String) % 2 == 1 ? 'c' . $String : $String; $String = base64_encode($this->decodeString($String)); $String = $this->convertBase64ToHex($String); return gmp_strval(gmp_init($String, 16)); }
private function makeId32($timestamp, $machine, $sequence) { $timestamp = gmp_mul((string) $timestamp, gmp_pow(2, 22)); $machine = gmp_mul((string) $machine, gmp_pow(2, 12)); $sequence = gmp_init((string) $sequence, 10); $value = gmp_or(gmp_or($timestamp, $machine), $sequence); return gmp_strval($value, 10); }
private function diffieHellman($publicKeyPoints, $privateKey) { $ecdsa = new BitcoinECDSA(); $normalizedPublicKey = ['x' => '0x' . $publicKeyPoints['x'], 'y' => '0x' . $publicKeyPoints['y']]; $product = $ecdsa->mulPoint($privateKey, $normalizedPublicKey); $secretPoints = ['x' => gmp_strval($product['x'], 16), 'y' => gmp_strval($product['y'], 16)]; return $secretPoints; }
/** * 与えられた値を、浮動小数点型に変換して返します。 * @link https://heycam.github.io/webidl/#idl-unrestricted-double Web IDL (Second Edition) * @link http://www.w3.org/TR/WebIDL/#idl-unrestricted-double Web IDL * @param boolean|integer|float|string|resource|\GMP|\SplFloat $value * @throws \InvalidArgumentException 配列、NULL が与えられた場合。または、GMP、SplFloat 以外のオブジェクトが与えられた場合。 * @return float */ public static function toUnrestrictedDouble($value) { if (self::isFloatCastable($value)) { return (double) ($value instanceof \GMP || is_resource($value) && get_resource_type($value) === 'GMP integer' ? gmp_strval($value) : $value); } else { throw new \InvalidArgumentException(ErrorMessageCreator::create($value, 'double (a float)')); } }
/** * @dataProvider vectorsP521 * @group large */ public function testP521($k, $x, $y) { $base = new \fpoirotte\Pssht\ECC\Point('0x00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66', '0x011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650'); $expected = new \fpoirotte\Pssht\ECC\Point($x, $y); $actual = $base->multiply(\fpoirotte\Pssht\ECC\Curve::getCurve('nistp521'), $k); $this->assertSame(gmp_strval($expected->x, 16), gmp_strval($actual->x, 16)); $this->assertSame(gmp_strval($expected->y, 16), gmp_strval($actual->y, 16)); }
public static function gmp_dechex($dec) { if (extension_loaded('gmp') && USE_EXT == 'GMP') { $hex = gmp_strval(gmp_init($dec), 16); return $hex; } else { throw new Exception("PLEASE INSTALL GMP"); } }
public function generate($serial) { $mul = gmp_mul(strval($this->mulFactor), strval($serial)); $add = gmp_add($mul, $this->diffFactor); $mod = gmp_mod($add, strval($this->amount)); $num = gmp_strval($mod); // $num = ($this->mulFactor * $serial + $this->diffFactor) % $this->amount; return str_pad($num, $this->length, $this->padding, STR_PAD_LEFT); }
/** * This will return either the integer value of the number or the string value * (if the integer value is too large). Use this when you prefer to receive * an integer, but you also don't want the number to be rounded down to the * maximum integer size if it is too large. * * @return string || int */ public function GetValue() { $comparison = gmp_cmp($this->number, $this->int_max); if ($comparison > 0) { return gmp_strval($this->number); } else { return gmp_intval($this->number); } }