php rsa 实现
PHP RSA 加密与解密实现
生成密钥对
使用 openssl_pkey_new 生成 RSA 密钥对,并通过 openssl_pkey_export 导出私钥。公钥可从密钥对中提取。
$config = [
"digest_alg" => "sha512",
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
];
$keyPair = openssl_pkey_new($config);
openssl_pkey_export($keyPair, $privateKey);
$publicKey = openssl_pkey_get_details($keyPair)["key"];
加密数据
使用公钥加密数据,openssl_public_encrypt 函数将明文加密为二进制密文,通常需要 Base64 编码以便传输。

$plaintext = "Sensitive data";
openssl_public_encrypt($plaintext, $encrypted, $publicKey);
$encryptedBase64 = base64_encode($encrypted);
解密数据
使用私钥解密数据,先对 Base64 密文解码,再通过 openssl_private_decrypt 还原明文。
$encryptedData = base64_decode($encryptedBase64);
openssl_private_decrypt($encryptedData, $decrypted, $privateKey);
echo $decrypted; // 输出: Sensitive data
签名与验证
用私钥生成签名,公钥验证签名完整性。

openssl_sign($plaintext, $signature, $privateKey, OPENSSL_ALGO_SHA256);
$isValid = openssl_verify($plaintext, $signature, $publicKey, OPENSSL_ALGO_SHA256);
echo $isValid === 1 ? "Valid" : "Invalid";
密钥存储
生成的密钥可保存为文件:
file_put_contents('private.pem', $privateKey);
file_put_contents('public.pem', $publicKey);
加载现有密钥:
$privateKey = openssl_pkey_get_private(file_get_contents('private.pem'));
$publicKey = openssl_pkey_get_public(file_get_contents('public.pem'));
注意事项
- 密钥长度建议至少 2048 位以保证安全。
- 加密数据长度受密钥长度限制,长数据需分段处理或使用混合加密(如 AES+RSA)。
- 敏感操作需处理
openssl_error_string()返回的错误信息。 - 生产环境建议使用专业库如
phpseclib进行更复杂的操作。






