rsa php实现
RSA 加密算法在 PHP 中的实现
RSA 是一种非对称加密算法,广泛应用于数据加密和数字签名。以下是 PHP 中实现 RSA 加密和解密的方法。
生成 RSA 密钥对
使用 openssl_pkey_new 函数生成 RSA 密钥对:
$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)["key"];
private_key_bits 指定密钥长度,通常为 2048 或 4096 位。
加密数据
使用公钥加密数据:

$data = "Sensitive data to encrypt";
openssl_public_encrypt($data, $encrypted, $publicKey);
$encryptedBase64 = base64_encode($encrypted);
加密后的数据是二进制格式,通常需要 Base64 编码以便传输。
解密数据
使用私钥解密数据:

$encrypted = base64_decode($encryptedBase64);
openssl_private_decrypt($encrypted, $decrypted, $privateKey);
签名和验证
RSA 也可用于数字签名:
openssl_sign($data, $signature, $privateKey, OPENSSL_ALGO_SHA256);
$signatureBase64 = base64_encode($signature);
$verified = openssl_verify($data, base64_decode($signatureBase64), $publicKey, OPENSSL_ALGO_SHA256);
密钥存储
生成的密钥可以保存到文件中:
file_put_contents('private.pem', $privateKey);
file_put_contents('public.pem', $publicKey);
使用时从文件读取:
$privateKey = file_get_contents('private.pem');
$publicKey = file_get_contents('public.pem');
注意事项
密钥长度至少应为 2048 位以保证安全性。 加密的数据长度不能超过密钥长度减去填充长度(例如 2048 位密钥最多加密 245 字节)。 敏感数据应使用 HTTPS 等安全通道传输。 私钥必须严格保密,公钥可以自由分发。






