PHP+JS+rsa数据加密传输实现代码

2019-04-09 09:46:40刘景俊

echo "10001";
echo "<br>";
echo "private:(php)(10)(private key)<br>";
echo $private;
echo "<br>";
echo "private:(js)(16)(private key)<br>";
echo $private_js;
//function
function read_ssl_key($filename)
{
exec("openssl rsa -in $filename -text -noout", $raw);
// read the key length
$keylength = (int) expect($raw[0], "Private-Key: (");
// read the modulus
expect($raw[1], "modulus:");
for($i = 2; $raw[$i][0] == ' '; $i++) $modulusRaw .= 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
相关文章 大家在看