rsa php实现
RSA 算法简介
RSA 是一种非对称加密算法,广泛应用于数据加密和数字签名。它基于大数分解的数学难题,使用公钥加密、私钥解密的机制。
PHP 实现 RSA 加密解密
生成密钥对
使用 openssl_pkey_new 生成 RSA 密钥对:
$config = array(
"digest_alg" => "sha512",
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
$res = openssl_pkey_new($config);
openssl_pkey_export($res, $privateKey);
$publicKey = openssl_pkey_get_details($res)["key"];
加密数据
使用公钥加密数据:
$data = "Secret message";
openssl_public_encrypt($data, $encrypted, $publicKey);
$encryptedBase64 = base64_encode($encrypted);
解密数据
使用私钥解密数据:
openssl_private_decrypt(base64_decode($encryptedBase64), $decrypted, $privateKey);
echo $decrypted; // 输出: Secret message
RSA 签名与验证
生成签名
使用私钥生成签名:
openssl_sign($data, $signature, $privateKey, OPENSSL_ALGO_SHA256);
$signatureBase64 = base64_encode($signature);
验证签名
使用公钥验证签名:

$isValid = openssl_verify($data, base64_decode($signatureBase64), $publicKey, OPENSSL_ALGO_SHA256);
echo $isValid === 1 ? "Valid" : "Invalid";
注意事项
- 密钥长度建议至少 2048 位以保证安全性
- 存储私钥时需要严格保密
- 实际应用中应考虑使用 HTTPS 等安全传输协议
- 生产环境建议使用专业的加密库而非自行实现
完整示例代码
// 生成密钥
$config = array(
"digest_alg" => "sha512",
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
$res = openssl_pkey_new($config);
openssl_pkey_export($res, $privateKey);
$publicKey = openssl_pkey_get_details($res)["key"];
// 加密
$data = "Secret message";
openssl_public_encrypt($data, $encrypted, $publicKey);
$encryptedBase64 = base64_encode($encrypted);
// 解密
openssl_private_decrypt(base64_decode($encryptedBase64), $decrypted, $privateKey);
echo $decrypted;
// 签名
openssl_sign($data, $signature, $privateKey, OPENSSL_ALGO_SHA256);
$signatureBase64 = base64_encode($signature);
// 验证
$isValid = openssl_verify($data, base64_decode($signatureBase64), $publicKey, OPENSSL_ALGO_SHA256);
echo $isValid === 1 ? "Valid" : "Invalid";






