公钥用于对数据进行加密,私钥用于对数据进行解密;
私钥用于对数据进行签名,公钥用于对签名进行验证。
封装的RSA代码如下:
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|
|