rsa算法实现php
RSA算法简介
RSA是一种非对称加密算法,广泛应用于数据加密和数字签名。它基于大整数分解的数学难题,使用公钥加密、私钥解密的机制。
PHP实现RSA算法
在PHP中,可以通过openssl扩展来实现RSA加密。以下是一个完整的实现示例:

<?php
// 生成密钥对
$config = array(
"digest_alg" => "sha512",
"private_key_bits" => 4096,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
// 创建密钥对
$res = openssl_pkey_new($config);
// 提取私钥
openssl_pkey_export($res, $privateKey);
// 提取公钥
$publicKey = openssl_pkey_get_details($res);
$publicKey = $publicKey["key"];
// 要加密的数据
$data = "This is a secret message";
// 使用公钥加密
openssl_public_encrypt($data, $encrypted, $publicKey);
$encrypted = base64_encode($encrypted);
// 使用私钥解密
openssl_private_decrypt(base64_decode($encrypted), $decrypted, $privateKey);
echo "Original: ".$data."\n";
echo "Encrypted: ".$encrypted."\n";
echo "Decrypted: ".$decrypted."\n";
?>
密钥生成与存储
生成的密钥可以保存到文件中以便后续使用:

// 保存私钥到文件
file_put_contents('private.key', $privateKey);
// 保存公钥到文件
file_put_contents('public.key', $publicKey);
// 从文件读取密钥
$privateKey = file_get_contents('private.key');
$publicKey = file_get_contents('public.key');
签名与验证
RSA也可用于数字签名:
// 创建签名
openssl_sign($data, $signature, $privateKey, OPENSSL_ALGO_SHA256);
$signature = base64_encode($signature);
// 验证签名
$verify = openssl_verify($data, base64_decode($signature), $publicKey, OPENSSL_ALGO_SHA256);
if ($verify == 1) {
echo "Signature is valid";
} else {
echo "Signature is invalid";
}
注意事项
PHP的openssl扩展需要启用,可以通过php.ini文件中的extension=openssl来开启。密钥长度建议至少2048位,更高安全性可使用4096位。加密数据长度不能超过密钥长度减去11字节。
对于大量数据的加密,建议使用对称加密算法如AES加密数据,再用RSA加密对称密钥。






