用php写的rsa加密解密

一个简单的公钥和私钥的加密解密代码,加密的源数据最长是117

<?php 
header("Content-type:text/html;charset=utf-8");
// $fp=fopen("rsa_private_key.pem","r"); //你的私钥文件路径
// $private_key=fread($fp,8192);
// fclose($fp);
// $fp1=fopen("rsa_public_key.pem","r"); //你的公钥文件路径
// $public_key=fread($fp1,8192);
// fclose($fp1);
//echo $private_key; 
$private_key='-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQC/1G9VD4KkdqygtBHoFbcy4NHGJLX0sN6WFs5paLi0KGeP3DCU
mymDPZPtoHD98tCQ5rZ6AupDlLHr8p1jGFAR1cBKLC1HJE6Dg/n0j+j+gDggp5VK
jcTKIOku45HWjFoIXJFyGPFwkAlg24cI4Rio/8LCEAQBjlu6i1nqM1P8lQIDAQAB
AoGBAKhQXgs1W7ywQBGVTezkOOUUbBs+FMUI95SbmCrW7tFsbknEun95kTgNLKGg
V+QKTEQHmu59Zk07x80uCDhtmbo03XZDCt2Uz1nifDCJH/eOK+XJQLPYuwFf1Vrt
wcrhG0y5kE4U280E/jTAckc01h1enDZ926yp7xcuDxSYfr61AkEA+PFZfAucx/b3
D1B3TpPCn5dzhzwUkgjaoj55mhFhVTo7cNJG/DBpTmddd3iI0LQRdwnhjzEDHjQw
WtLQ9LjHkwJBAMVEmZjNgfTSP/6NPdqMeZpemcp5CZB7qZGg/HW196YVZ+uYYnnX
Fpgfymcw0BrgNmhD0lUWa7HoAXFsKniT9DcCQQCPA4hW/QzazARvJdkEqVp7+LQE
Ev32T2PbJW0Sl72FCukvDX5+TwmQY02M3xAqZehKrMCKVKvn5C+LXeVxUd5FAkAh
484rdSrdX32FAsjckgOWJKhxI2gkPUp9bVXR9ygLjWPkErLgUbZc/iEspzMpWtme
AgDRg1+PGdedn8KQIoLzAkBZR//XnzjDg+E0xd0BpWo8lkjny6FFSPwWYbiJDR9E
C5iT8FVm4N5300Pm4ogMdp92T2R6HcIkYl9wPUW5U4FV
-----END RSA PRIVATE KEY-----';
$public_key='-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC/1G9VD4KkdqygtBHoFbcy4NHG
JLX0sN6WFs5paLi0KGeP3DCUmymDPZPtoHD98tCQ5rZ6AupDlLHr8p1jGFAR1cBK
LC1HJE6Dg/n0j+j+gDggp5VKjcTKIOku45HWjFoIXJFyGPFwkAlg24cI4Rio/8LC
EAQBjlu6i1nqM1P8lQIDAQAB
-----END PUBLIC KEY-----';
$pi_key=openssl_pkey_get_private($private_key);//这个函数可用来判断私钥是否是可用的,可用返回资源id Resource id 
$pu_key=openssl_pkey_get_public($public_key );//这个函数可用来判断公钥是否是可用的
print_r($pi_key);echo "\n"; echo "<br>";
print_r($pu_key);echo "\n"; echo "<br>";
echo "<hr>";
$data='http://www.yiecho.com';
$encrypted = ""; 
$decrypted = ""; 
echo strlen($data);
echo "加密的源数据:".$data."\n"; echo "<br>";
echo "private key encrypt:\n"; echo "<br>";
openssl_private_encrypt($data,$encrypted,$pi_key);//私钥加密 
$encrypted = base64_encode($encrypted);//加密后的内容通常含有特殊字符,需要编码转换下,在网络间通过url传输时要注意base64编码是否是url安全的 
echo '私钥加密后:'.$encrypted."\n"; echo "<br>";echo "<br>";
echo "public key decrypt:\n"; echo "<br>";
openssl_public_decrypt(base64_decode($encrypted),$decrypted,$pu_key);//私钥加密的内容通过公钥可用解密出来 
echo '公钥解密后:'.$decrypted."\n"; echo "<br>";
echo "<hr>";
echo "public key encrypt:\n"; echo "<br>";
openssl_public_encrypt($data,$encrypted,$pu_key);//公钥加密 
$encrypted = base64_encode($encrypted); 
echo $encrypted,"\n"; echo "<br>";
echo "private key decrypt:\n"; echo "<br>";
openssl_private_decrypt(base64_decode($encrypted),$decrypted,$pi_key);//私钥解密 
echo $decrypted,"\n"; echo "<br>";
?>

大部分的代码已经做了注释,可以直接用

用php写的rsa加密解密:等您坐沙发呢!

发表评论

表情
还能输入210个字