usRaw .= trim($raw[$i]);
// read the public exponent
$public = (int) expect($raw[$i], "publicExponent: ");
// read the private exponent
expect($raw[$i + 1], "privateExponent:");
for($i += 2; $raw[$i][0] == '' ''; $i++) $privateRaw .= trim($raw[$i]);
// Just to make sure
expect($raw[$i], "prime1:");
// Conversion to decimal format for bcmath
$modulus = bc_hexdec($modulusRaw);
$private = bc_hexdec($privateRaw);
return array($keylength, $modulus[''php''], $public, $private[''php''],$modulus[''js''], $private[''js'']);
}
/*
* Convert a hexadecimal number of the form "XX:YY:ZZ:..." to decimal
* Uses BCmath, but the standard normal hexdec function for the components
*/
function bc_hexdec($hex)
{
$coefficients = explode(":", $hex);
$result_js= implode("",$coefficients);
$i = 0;
$result = 0;
foreach(array_reverse($coefficients) as $coefficient)
{
$mult = bcpow(256, $i++);
$result = bcadd($result, bcmul(hexdec($coefficient), $mult));
}
return array(''php''=>$result,''js''=>$result_js);
}
/*
* If the string has the given prefix, return the remainder.
* If not, die with an error
*/
function expect($str, $prefix)
{
if(substr($str, 0, strlen($prefix)) == $prefix)
return substr($str, strlen($prefix));
else
die("Error: expected $prefix");
}
整套加密及解密的方法都在上面了,本人的测试环境为php5.3+WIN7
上面所有文件下载:RSAFILE