PHP实现非对称加密
#生成私钥
openssl genrsa -out rsa_private_key.pem 1024
#生成公钥
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
在PHP中用RSA进行加密解密如下。
$private_key_file = "rsa_private_key.pem";
$public_key_file = "rsa_public_key.pem";
$data = "Hello World";
if (file_exists($private_key_file)) {
$private_key = file_get_contents($private_key_file);
} else {
die('private key not exists');
}
if (file_exists($public_key_file)) {
$public_key = file_get_contents($public_key_file);
} else {
die('public key not exists');
}
$encrypted = $decrypted = "";
openssl_private_encrypt($data, $encrypted, $private_key);//使用私钥加密数据
openssl_public_decrypt($encrypted, $decrypted, $public_key);
//使用公钥界面数据
echo $decrypted;
$encrypted = $decrypted = "";
openssl_public_encrypt($data, $encrypted, $public_key);
//使用公钥进行加密
openssl_private_decrypt($data, $decrypted, $private_key);//使用私钥进行加密
echo $decrypted;