/** returns RSA key pair with length $bit_len */ function generate_key_pair($bit_len) { // generate two primes p and q $p_len = (int) ($bit_len / 2) + 1; $q_len = $bit_len - $p_len; $p = get_prime($p_len); $q = get_prime($q_len); // $n - is shared modulus $n = bi_mul($p, $q); // generate public ($e) and private ($d) keys $pq = bi_mul(bi_dec($p), bi_dec($q)); do { $e = bi_rand($q_len, 'microtime_generator'); } while (!bi_is_zero(bi_dec(bi_gcd($e, $pq)))); $d = bi_invmod($e, $pq); return array('n' => bi_serialize($n), 'public_key' => bi_serialize($e), 'private_key' => bi_serialize($d)); }
/** * Transforms large integer into binary representation. * * Example of transformation: * $num = 0x9078563412; * $str = "\x12\x34\x56\x78\x90"; * * @param big_int resource $num * @return string * @access public */ function int2bin($num) { return bi_serialize($num); }
echo 'pow($a, 4) = [', bi_to_str($c), "]<br/>\n"; // argument of bi_fact() must have integer type (not BIG_INT) $c = bi_fact(100); echo '100! = [', bi_to_str($c), "]<br/>\n"; $c = bi_sqrt($a); echo 'sqrt($a) = [', bi_to_str($c), "]<br/>\n"; $c = bi_sqrt_rem($a); echo 'sqrt_rem($a) = [', bi_to_str($c), "]<br/>\n"; $c = bi_gcd($a, $b); echo 'GCD($a, $b) = [', bi_to_str($c), "]<br/>\n"; // Miller-Rabin primality test of $a echo 'miller_test($a, $b) = ', bi_miller_test($a, $b), "<br/>\n"; // primality test of $a echo 'is_prime($a) = ', bi_is_prime($a), "<br/>\n"; // Jacobi symbol ($a|$b) echo 'jacobi($a, $b) = ', bi_jacobi($a, $b), "<br/>\n"; $c = bi_div_extended($a, $b); echo '$a = $b * ', bi_to_str($c[0]), ' + ', bi_to_str($c[1]), "<br/>\n"; $c = bi_gcd_extended($a, $b); echo 'abs($a) * ', bi_to_str($c[1]), ' + abs($b) * ', bi_to_str($c[2]), ' = ', bi_to_str($c[0]), "<br/>\n"; // serialize $a into sequence of bytes $str = bi_serialize($a); echo '$str = serialize($a) = [', base64_encode($str), "]<br/>\n"; // unserialize $a from sequence of bytes $a = bi_unserialize($str); echo 'unserialize($str) = [', bi_to_str($a), "]<br/>\n"; // show package info var_dump(bi_info()); echo 'the list of all functions in BIG_INT module:', "<br/>\n"; echo implode(", ", get_extension_funcs('big_int')); echo "<br/>\n";