PHP实现RSA加密,解密,加签,验签
<p style="font-size: 16px; color: black; line-height: 40px; text-align: left; margin-bottom: 15px;">公钥用于对数据进行加密,私钥用于对数据进行解密;</p>
<p style="font-size: 16px; color: black; line-height: 40px; text-align: left; margin-bottom: 15px;">私钥用于对数据进行签名,公钥用于对签名进行验证。</p>
<p style="font-size: 16px; color: black; line-height: 40px; text-align: left; margin-bottom: 15px;">封装的RSA代码如下:</p>
<div style="color: black; text-align: left; margin-bottom: 10px;">class Rsa
{
/**
* private key
*/
private $_privKey;
/**
* public key
*/
private $_pubKey;
/**
* the keys saving path
*/
private $_keyPath;
public function __construct ($path)
{
if (empty($path) || !is_dir($path)) {
throw new \Exception(Must set the keys save path);
}
//设置私钥
$this->_keyPath = $path;
$file = $this->_keyPath . DIRECTORY_SEPARATOR . rsa_private_key.pem;
$prk = file_get_contents($file);
$this->_privKey = openssl_pkey_get_private($prk);
//设置公钥
$file = $this->_keyPath . DIRECTORY_SEPARATOR . rsa_public_key.pem;
$puk = file_get_contents($file);
$this->_pubKey = openssl_pkey_get_public($puk);
}
/**
* setup the private key
*/
public function setupPrivKey ()
{
if (is_resource($this->_privKey)) {
return true;
}
$file = $this->_keyPath . DIRECTORY_SEPARATOR . rsa_private_key.pem;
$prk = file_get_contents($file);
$this->_privKey = openssl_pkey_get_private($prk);
return true;
}
/**
* setup the public key
*/
public function setupPubKey ()
{
if (is_resource($this->_pubKey)) {
return true;
}
$file = $this->_keyPath . DIRECTORY_SEPARATOR . rsa_public_key.pem;
$puk = file_get_contents($file);
$this->_pubKey = openssl_pkey_get_public($puk);
return true;
}
/**
* @function 私钥加密
* @param $data
* @return string|</div>
谷歌外链发布 http://www.fok120.com/
页:
[1]