/** * Generates prime number with length $bits_cnt * using $random_generator as random generator function. * * @param int $bits_cnt * @param string $rnd_generator * @access public */ function getPrime($bits_cnt, $random_generator) { $bytes_n = intval($bits_cnt / 8); $bits_n = $bits_cnt % 8; do { $str = ''; for ($i = 0; $i < $bytes_n; $i++) { $str .= chr(call_user_func($random_generator) & 0xff); } $n = call_user_func($random_generator) & 0xff; $n |= 0x80; $n >>= 8 - $bits_n; $str .= chr($n); $num = $this->bin2int($str); // search for the next closest prime number after [$num] $num = bi_next_prime($num); } while ($this->bitLen($num) != $bits_cnt); return $num; }
Returns pseudorandom number with $bit_len bit length. Attention: do not use this function in cryptographic or security applications! The function can be used only for educational purposes :) */ $c = bi_rand(100); echo 'rand(100) = ', bi_to_str($c), "<br/>\n"; $c = bi_rand(100, 'mt_rand'); // use mt_rand() as random generator echo 'rand(100, "mt_rand") = ', bi_to_str($c), "<br/>\n"; /* functions for modular arithmetic calculations */ echo '<h3>modular arithmetic functions</h3>' . "\n"; // find next pseudoprime number after $c $modulus = bi_next_prime($c); echo '$modulus = next_prime($c) = [', bi_to_str($modulus), "]<br/>\n"; $c = bi_addmod($a, $b, $modulus); echo '$a + $b (mod $modulus) = [', bi_to_str($c), "]<br/>\n"; $c = bi_submod($a, $b, $modulus); echo '$a - $b (mod $modulus) = [', bi_to_str($c), "]<br/>\n"; $c = bi_mulmod($a, $b, $modulus); echo '$a * $b (mod $modulus) = [', bi_to_str($c), "]<br/>\n"; $c = bi_divmod($a, $b, $modulus); echo '$a / $b (mod $modulus) = [', bi_to_str($c), "]<br/>\n"; $c = bi_powmod($a, $b, $modulus); echo 'pow($a, $b) (mod $modulus) = [', bi_to_str($c), "]<br/>\n"; $c = bi_factmod(1000, $modulus); echo '1000! (mod $modulus) = [', bi_to_str($c), "]<br/>\n"; $c = bi_absmod(-1, $modulus); echo '-1 (mod $modulus) = [', bi_to_str($c), "]<br/>\n";
/** * Finds next strong pseudoprime number, following after $num * * @param big_int resource $num * @return big_int resource * @access public */ function nextPrime($num) { return bi_next_prime($num); }
/** returns a "good" prime $a with length $bit_len with resrtiction: $a - 1 != 0 (mod $e) */ function get_prime($bit_len) { return bi_next_prime(bi_set_bit(bi_rand($bit_len, 'microtime_generator'), $bit_len - 1)); }