<?php
//测试密钥-公钥
$pubKey="-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANSlDRoxEXWQrbIbFig3SuT/YH/K0q5/
OLBVloeXSr+dc+PWvXsRnwkxIkX5KznPCG9zLGe/Ga9XRyp+k2YrnrsCAwEAAQ==
-----END PUBLIC KEY-----";
//私钥
$privKey="-----BEGIN RSA PRIVATE KEY-----
MIIBOQIBAAJBANSlDRoxEXWQrbIbFig3SuT/YH/K0q5/OLBVloeXSr+dc+PWvXsR
nwkxIkX5KznPCG9zLGe/Ga9XRyp+k2YrnrsCAwEAAQJACg70m7SOet0pGi+l0Kks
5cAetGzHonFqIQ0rXaaOZpnZ7VeBTjklFVlVv/6UGr0h7jLclU+0UcEZ1lxwQUBx
wQIhAPoD6k+WOJld9D0p6ECLlS0ii4spj/T5o5ODdI+pkS2JAiEA2bwhZICOwb8w
FjfJOoKFcfuUfTk0n8y1DokfRQBC/SMCIBoZ8opgioQodOk1yNOEPwy5QIxEyIyw
y00JOlANSeTRAiBm+oeAlRzvnZEMsQ3HUnvy0N4F68xr19G6MjhL1jfYqQIgGiYa
RlI1jeOWFLKyxOFcNim8HUhfqIebm8Mccc0/3kQ=
-----END RSA PRIVATE KEY-----";
function pubEncrypt($data,$pubKey){ //公钥加密
$pubKey = openssl_pkey_get_public($pubKey);
openssl_public_encrypt($data, $encrypted, $pubKey);
return base64_encode($encrypted);
}
function privDecrypt($data,$privKey){ //私钥解密
$privKey=openssl_pkey_get_private($privKey);
$encrypted = base64_decode($data);
openssl_private_decrypt($encrypted, $decrypted, $privKey);
return $decrypted;
}
function privEncrypt($data,$privKey){ //私钥加密
$privKey=openssl_pkey_get_private($privKey);
openssl_private_encrypt($data, $encrypted, $privKey);
return base64_encode($encrypted);
}
function pubDecrypt($data,$pubKey){ //公钥解密
$pubKey = openssl_pkey_get_public($pubKey);
$encrypted = base64_decode($data);
openssl_public_decrypt($encrypted, $decrypted, $pubKey);
return $decrypted;
}
$string='一二三四五六七八九十';
echo '公钥加密:';
$en = pubEncrypt($string,$pubKey);
echo $en . '<br /> 私钥解密:';
$de = privDecrypt($en,$privKey);
echo $de;
echo "<br>";
$string='一二三四五六七八九十';
echo '私钥加密:';
$en = privEncrypt($string,$privKey);
echo $en . '<br /> 公钥解密:';
$de = pubDecrypt($en,$pubKey);
echo $de;
?>
有何疑问?