/**
  * {@inheritDoc}
  * @see \Mdanter\Ecc\RandomNumberGeneratorInterface::generate()
  */
 public function generate($max)
 {
     $random = gmp_strval(gmp_random());
     $small_rand = rand();
     while (gmp_cmp($random, $max) > 0) {
         $random = gmp_div($random, $small_rand, GMP_ROUND_ZERO);
     }
     return gmp_strval($random);
 }
function randomBytes($length = 16, $secure = true, $raw = true, $startEntropy = "", &$rounds = 0, &$drop = 0)
{
    static $lastRandom = "";
    $output = "";
    $length = abs((int) $length);
    $secureValue = "";
    $rounds = 0;
    $drop = 0;
    while (!isset($output[$length - 1])) {
        //some entropy, but works ^^
        $weakEntropy = array(is_array($startEntropy) ? implode($startEntropy) : $startEntropy, serialize(stat(__FILE__)), __DIR__, PHP_OS, microtime(), (string) lcg_value(), (string) PHP_MAXPATHLEN, PHP_SAPI, (string) PHP_INT_MAX . "." . PHP_INT_SIZE, serialize($_SERVER), serialize(get_defined_constants()), get_current_user(), serialize(ini_get_all()), (string) memory_get_usage() . "." . memory_get_peak_usage(), php_uname(), phpversion(), extension_loaded("gmp") ? gmp_strval(gmp_random(4)) : microtime(), zend_version(), (string) getmypid(), (string) getmyuid(), (string) mt_rand(), (string) getmyinode(), (string) getmygid(), (string) rand(), function_exists("zend_thread_id") ? (string) zend_thread_id() : microtime(), var_export(@get_browser(), true), function_exists("getrusage") ? @implode(getrusage()) : microtime(), function_exists("sys_getloadavg") ? @implode(sys_getloadavg()) : microtime(), serialize(get_loaded_extensions()), sys_get_temp_dir(), (string) disk_free_space("."), (string) disk_total_space("."), uniqid(microtime(), true), file_exists("/proc/cpuinfo") ? file_get_contents("/proc/cpuinfo") : microtime());
        shuffle($weakEntropy);
        $value = hash("sha512", implode($weakEntropy), true);
        $lastRandom .= $value;
        foreach ($weakEntropy as $k => $c) {
            //mixing entropy values with XOR and hash randomness extractor
            $value ^= hash("sha256", $c . microtime() . $k, true) . hash("sha256", mt_rand() . microtime() . $k . $c, true);
            $value ^= hash("sha512", (string) lcg_value() . $c . microtime() . $k, true);
        }
        unset($weakEntropy);
        if ($secure === true) {
            $strongEntropyValues = array(is_array($startEntropy) ? hash("sha512", $startEntropy[($rounds + $drop) % count($startEntropy)], true) : hash("sha512", $startEntropy, true), file_exists("/dev/urandom") ? fread(fopen("/dev/urandom", "rb"), 64) : str_repeat("", 64), (function_exists("openssl_random_pseudo_bytes") and version_compare(PHP_VERSION, "5.3.4", ">=")) ? openssl_random_pseudo_bytes(64) : str_repeat("", 64), function_exists("mcrypt_create_iv") ? mcrypt_create_iv(64, MCRYPT_DEV_URANDOM) : str_repeat("", 64), $value);
            $strongEntropy = array_pop($strongEntropyValues);
            foreach ($strongEntropyValues as $value) {
                $strongEntropy = $strongEntropy ^ $value;
            }
            $value = "";
            //Von Neumann randomness extractor, increases entropy
            $bitcnt = 0;
            for ($j = 0; $j < 64; ++$j) {
                $a = ord($strongEntropy[$j]);
                for ($i = 0; $i < 8; $i += 2) {
                    $b = ($a & 1 << $i) > 0 ? 1 : 0;
                    if ($b != (($a & 1 << $i + 1) > 0 ? 1 : 0)) {
                        $secureValue |= $b << $bitcnt;
                        if ($bitcnt == 7) {
                            $value .= chr($secureValue);
                            $secureValue = 0;
                            $bitcnt = 0;
                        } else {
                            ++$bitcnt;
                        }
                        ++$drop;
                    } else {
                        $drop += 2;
                    }
                }
            }
        }
        $output .= substr($value, 0, min($length - strlen($output), $length));
        unset($value);
        ++$rounds;
    }
    $lastRandom = hash("sha512", $lastRandom, true);
    return $raw === false ? bin2hex($output) : $output;
}
Beispiel #3
0
 public static function generateNewS()
 {
     // S is a random 32 byte array
     // gmp_random generates 16 bit per limiter; 32byte/16bit = 32*8/16 = 16
     $random = gmp_random(16);
     $random_str = gmp_strval($random, 16);
     $s_str = sha1($random_str);
     // sha1 is just 20 bytes long, add 12 more bytes = 24 (hexencoded)
     $s_str .= substr($random_str, 0, 24);
     return $s_str;
 }
 public static function gmp_random($n)
 {
     if (extension_loaded('gmp') && USE_EXT == 'GMP') {
         $random = gmp_strval(gmp_random());
         $small_rand = rand();
         while (gmp_cmp($random, $n) > 0) {
             $random = gmp_div($random, $small_rand, GMP_ROUND_ZERO);
         }
         return gmp_strval($random);
     } else {
         throw new Exception("PLEASE INSTALL GMP");
     }
 }
Beispiel #5
0
 /**
  * Large random number generator
  *
  * @param integer $powerOfTwo
  * @return string
  */
 public function random($powerOfTwo)
 {
     $prefix = 'P';
     if (extension_loaded('bcmath')) {
         OauthHelper::log($prefix . OauthHelper::bcrandom(1, bcpow(2, $powerOfTwo)));
         return $prefix . OauthHelper::bcrandom(1, bcpow(2, $powerOfTwo));
     }
     if (extension_loaded('gmp')) {
         $limbOp = round($powerOfTwo / 32);
         OauthHelper::log($prefix . gmp_strval(gmp_random($limbOp)));
         return $prefix . gmp_strval(gmp_random($limbOp));
     }
     return $prefix . rand(0, pow(2, $powerOfTwo));
 }
Beispiel #6
0
 function _getRandomString($length)
 {
     assert('$length >= 0');
     $rv = '';
     $len = 0;
     while ($len < $length) {
         $a = unpack('C*', pack('L2', gmp_random(2)));
         // untested
         for ($i = 1; $i < 9; ++$i) {
             $rv .= chr($a[$i] & 0xff);
             if (++$len == $length) {
                 return $rv;
             }
         }
     }
     return $rv;
 }
Beispiel #7
0
 /**
  * Constructor
  *
  * @param	String	Private key, if not included one shall be generated
  */
 function Diffie_Hellman_GMP($privkey = "")
 {
     if (empty($privkey)) {
         $privkey = gmp_random(5);
     }
     $this->privatekey = $privkey;
 }
Beispiel #8
0
 function random($minval)
 {
     if (function_exists('gmp_random')) {
         $limb_cnt = 31;
         do {
             $rdm = gmp_random($limb_cnt--);
         } while (gmp_cmp($minval, $rdm) > 0);
         return gmp_strval($rdm);
     } else {
         // FIXME: does not honor minval
         return rand(0, getrandmax());
     }
 }
Beispiel #9
0
            #echo "New dIC : $deviceID\n";
            $changed = $dbHandle->exec("UPDATE {$dbTable} SET {$dbIDCol} = " . $dbHandle->quote($deviceID) . " WHERE {$dbEmailCol} = " . $email . " AND {$dbKeyCol} = " . $cdkey);
            #echo "Changed rows : $changed\n";
            $cdKeyResponse = $cdKeyPositive;
        } else {
            $cdKeyResponse = $cdKeyNegative;
        }
    }
}
if (!file_exists($client_pub_file)) {
    exit("Decoder : client keys are missing!");
}
$cpb = explode(" ", file_get_contents($client_pub_file));
$cp = gmp_init($cpb[0]);
$cg = gmp_init($cpb[1]);
$cy = gmp_init($cpb[2]);
$cdKeyResponse = mb_convert_encoding($cdKeyResponse, "UTF-8");
$cdKeyCode = "";
for ($i = 0; $i < strlen($cdKeyResponse); $i++) {
    $charCode = unpack("N", mb_convert_encoding($cdKeyResponse[$i], "UCS-4BE", "UTF-8"));
    $cc = decbin(reset($charCode));
    while (strlen($cc) < 8) {
        $cc = "0" . $cc;
    }
    $cdKeyCode = $cdKeyCode . $cc;
}
$cdKeyCode = gmp_init($cdKeyCode, 2);
$cdKeyCodeK = gmp_add(gmp_random(31), "2");
$cdKeyCodeA = gmp_powm($cg, $cdKeyCodeK, $cp);
$cdKeyCodeB = gmp_mod(gmp_mul(gmp_powm($cy, $cdKeyCodeK, $cp), $cdKeyCode), $cp);
echo gmp_strval($cdKeyCodeA) . " " . gmp_strval($cdKeyCodeB);
 function __construct($I, $P)
 {
     parent::__construct($I, $P);
     $this->a = gmp_random();
     $this->A = gmp_strval(gmp_powm($this->g, $this->a, $this->N), 16);
 }
Beispiel #11
0
 /**
  * This method returns a random number with the range of x and y.
  *
  * @access public
  * @static
  * @param IInteger\Type $x                                  the min operand
  * @param IInt32\Type $y                                    the max operand
  * @return IInteger\Type                                    the result
  */
 public static function random(IInteger\Type $x = null, IInt32\Type $y = null) : IInteger\Type
 {
     return IInteger\Type::box(gmp_strval(gmp_random(IInt32\Module::nvl($y, IInt32\Type::one())->unbox())));
 }
 function generatePrivate()
 {
     return gmp_random(60);
 }
Beispiel #13
0
 /**
  * associate
  *
  * The Relying Party and the OP establish an association -- a shared secret
  * established using Diffie-Hellman Key Exchange [RFC2631].
  *
  * @see 8. Establishing Associations
  */
 protected function associate()
 {
     /**
      * check if we have an association in the cache
      * @return array Association
      */
     if ($association = $this->cache($this->provider)) {
         return $association;
     }
     $private_key = gmp_random(16);
     $public_key = base64_encode($this->btwocEncode(gmp_strval(gmp_powm(self::OPENID_DH_GEN, $private_key, self::OPENID_DH_MODULUS))));
     /**
      * @see 8.1.1. Common Request Parameters
      */
     $params = array('openid.ns' => self::OPENID_NS_2_0, 'openid.mode' => 'associate', 'openid.assoc_type' => 'HMAC-SHA256', 'openid.session_type' => 'DH-SHA256', 'openid.dh_consumer_public' => $public_key);
     if ($this->request($this->provider, false, 'POST', $params)) {
         if (isset($this->headers['dh_server_public'], $this->headers['enc_mac_key'])) {
             $dh_server_public = base64_decode($this->headers['dh_server_public']);
             $enc_mac_key = $this->headers['enc_mac_key'];
             $ZZ = $this->btwocEncode(gmp_strval(gmp_powm($this->btwocDecode($dh_server_public), $private_key, self::OPENID_DH_MODULUS)));
             /**
              * decrypt & return the mac_key (shared secret)
              */
             $secret = $this->openidXOR(hash('sha256', $ZZ, true), base64_decode($enc_mac_key));
             /**
              * store association in cache
              */
             if ($this->cache($this->provider, json_encode(array_merge($this->headers, array('op_endpoint' => $this->provider, 'mac_key' => base64_encode($secret)))), $this->headers['expires_in'])) {
                 return array('assoc_handle' => $this->headers['assoc_handle']);
             } else {
                 return false;
             }
         } else {
             return false;
         }
     } else {
         return false;
     }
 }
Beispiel #14
0
<?php

var_dump(gmp_strval(gmp_random()));
var_dump(gmp_strval(gmp_random(-1)));
var_dump(gmp_strval(gmp_random(0)));
var_dump(gmp_strval(gmp_random(10)));
var_dump(gmp_strval(gmp_random("-10")));
var_dump(gmp_strval(gmp_random(-10)));
var_dump(gmp_random(array()));
var_dump(gmp_random(array(), 1));
var_dump(gmp_random(""));
var_dump(gmp_random("test"));
echo "Done\n";
Beispiel #15
0
 public static function nextPrimeBetween($lo = self::LO_MAX, $hi = self::HI_MAX)
 {
     # Sanitize PHP Bullfrogs
     $lo = preg_replace("[^0-9]", '', "{$lo}");
     $hi = preg_replace("[^0-9]", '', "{$hi}");
     if ($lo == $hi) {
         return $lo;
     } else {
         if ($lo < $hi || $hi > $lo) {
             # Swappish Sanity
             $t = $lo;
             $lo = $hi;
             $hi = $t;
         }
     }
     # Still unused :)
     if ($lo < self::LO_MAX || $hi > self::HI_MAX) {
         # Your prime is not in range!
         return self::NO_NO_NOOOO;
     }
     # Check how cool you are
     switch (GWF_Random::rand(0, 4)) {
         case 0:
             return self::NO_PRIME;
         case 1:
             return self::NO_CLUE;
             #			case 2: return self::NO_NEO;
         #			case 2: return self::NO_NEO;
         case 3:
             return self::NO_NO_NO;
         case 4:
         case 2:
             # Good Enough :)
             $the_value = '1';
             while ($the_value < self::HI_MAX) {
                 $the_value = gmp_strval(gmp_nextprime(gmp_random(2)));
             }
             return $the_value;
     }
 }
 function __construct()
 {
     $this->N = gmp_init('ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff', 16);
     $this->badb = gmp_random();
     $this->badB = gmp_strval(gmp_powm('2', $this->badb, $this->N), 16);
 }