$p = 17; $q = 19; $n = $p * $q; $phi = ($p - 1) * ($q - 1);
$e = mt_rand(2, $phi - 1); while (gcd($e, $phi) != 1) { $e = mt_rand(2, $phi - 1); }
function gcd($a, $b) { if ($b == 0) { return $a; } else { return gcd($b, $a % $b); } }
$d = modInverse($e, $phi); $public_key = array('e' =>$e, 'n' =>$n); $private_key = array('d' =>$d, 'n' =>$n); $plain_text = 'Hello, world!'; $cipher_text = encrypt($plain_text, $public_key); $recovered_text = decrypt($cipher_text, $private_key); function encrypt($message, $key) { $m = str2int($message); $e = $key['e']; $n = $key['n']; $c = bcpowmod($m, $e, $n); return int2str($c); } function decrypt($message, $key) { $c = str2int($message); $d = $key['d']; $n = $key['n']; $m = bcpowmod($c, $d, $n); return int2str($m); } function str2int($message) { $result = ''; for ($i = 0; $i< strlen($message); $i++) { $result .= str_pad(ord($message[$i]), 3, '0', STR_PAD_LEFT); } return $result; } function int2str($message) { $result = ''; while ($message >0) { $result .= chr($message % 1000); $message = intval($message / 1000); } return strrev($result); } function modInverse($a, $m) { $m0 = $m; $y = 0; $x = 1; if ($m == 1) { return 0; } while ($a >1) { // q is quotient $q = intval($a / $m); $t = $m; // m is remainder now, process // same as Euclid's algo $m = $a % $m; $a = $t; $t = $y; // Update x and y $y = $x - $q * $y; $x = $t; } // Make x positive if ($x< 0) { $x += $m0; } return $x; }
下一篇jpeg php