php 封装 rsa2 公私钥加密
时间: 2023-04-10 08:02:39 浏览: 169
可以使用openssl扩展来实现RSA加密和解密。以下是一个简单的PHP封装RSA2公私钥加密的示例代码:
```php
<?php
class RSA2Encryption {
private $publicKey;
private $privateKey;
public function __construct($publicKey, $privateKey) {
$this->publicKey = $publicKey;
$this->privateKey = $privateKey;
}
public function encrypt($data) {
$encrypted = '';
$publicKey = openssl_get_publickey($this->publicKey);
openssl_public_encrypt($data, $encrypted, $publicKey, OPENSSL_PKCS1_OAEP_PADDING);
return base64_encode($encrypted);
}
public function decrypt($encryptedData) {
$decrypted = '';
$privateKey = openssl_get_privatekey($this->privateKey);
openssl_private_decrypt(base64_decode($encryptedData), $decrypted, $privateKey, OPENSSL_PKCS1_OAEP_PADDING);
return $decrypted;
}
}
// Example usage
$publicKey = file_get_contents('public_key.pem');
$privateKey = file_get_contents('private_key.pem');
$rsa = new RSA2Encryption($publicKey, $privateKey);
$encryptedData = $rsa->encrypt('Hello, world!');
echo "Encrypted data: $encryptedData\n";
$decryptedData = $rsa->decrypt($encryptedData);
echo "Decrypted data: $decryptedData\n";
?>
```
请注意,此示例代码仅用于演示目的。在实际应用中,您需要采取更多的安全措施,例如使用密码保护私钥文件,以及使用更强的加密算法和密钥长度。
阅读全文