php openssl rsa 加密解密应用
1、生成公钥和私钥
生成私钥:
openssl genrsa 1024 > private.key
(注意,1024是密钥的长度,如果密钥较长,相应加密后的密文也会较长)
生成公钥:
openssl rsa -in private.key -pubout > public.key
2、加解密
<?php
class mycrypt {
public $pubkey;
public $privkey;
function __construct() {
$this->pubkey = file_get_contents('/home/openssl/public.key');
$this->privkey = file_get_contents('/home/openssl/private.key');
}
public function encrypt($data) {
if (openssl_public_encrypt($data, $encrypted, $this->pubkey))
$data = base64_encode($encrypted);
else
throw new Exception('Unable to encrypt data. Perhaps it is bigger than the key size?');
return $data;
}
public function decrypt($data) {
if (openssl_private_decrypt(base64_decode($data), $decrypted, $this->privkey))
$data = $decrypted;
else
$data = '';
return $data;
}
}
$rsa = new mycrypt();
echo $rsa -> encrypt('abc');
//echo $rsa -> decrypt('W+ducpssNJlyp2XYE08wwokHfT0bm87yBz9vviZbfjAGsy/U9Ns9FIed684lWjYyyofi/1YWrU0Mp8vLOYi8l6CfklBY=');
发表评论: