PHP rsa加密生成(加密通信)
2020-04-01 本文已影响0人
blank喵
<?php
/**
* User: orzblankcat
* Date: 2019/1/25
* Time: 17:30
*/
class RsaClass
{
protected $config = [
// "digest_alg" => 'sha512', //加密模式
"private_key_bits" => 4096, //字节数 512 1024 2048 4096 等
"private_key_type" => OPENSSL_KEYTYPE_RSA, //加密类型
"config" => "E:/phpStudy/PHPTutorial/Apache/conf/openssl.cnf",
"encrypt_key"=>true //私钥加密
];
protected $passphrase = '123456';//密码 当encrypt_key=>true必填
protected $pi_key='';
protected $pu_key='';
protected $priPath='Common/rsa/pri.key';
protected $pubPath='Common/rsa/pub.key';
public function __construct()
{
extension_loaded('openssl') or die('php需要openssl扩展支持');
if(!file_exists($this->pubPath)||!file_exists($this->priPath))
{
$this->createKey();
}
}
public function createKey()
{
$res = openssl_pkey_new($this->config);
//提取私钥
openssl_pkey_export($res, $private_key, $this->passphrase,$this->config);
//生成公钥
$public_key = openssl_pkey_get_details($res);
$public_key = $public_key["key"];
//显示数据
$pri = fopen($this->priPath, "w") or die("Unable to open file!");
fwrite($pri, $private_key);
$pub = fopen($this->pubPath, "w") or die("Unable to open file!");
fwrite($pub, $public_key);
fclose($pri);
fclose($pub);
}
/**
* 公钥加密数据
*/
public function pubEncryptKey($data)
{
$this->pu_key = openssl_pkey_get_public(file_get_contents($this->pubPath));
openssl_public_encrypt($data, $encrypted, $this->pu_key);
return base64_encode($encrypted);
}
/**
* 公钥解密数据
*/
public function pubDecodeKey($data)
{
$this->pu_key = openssl_pkey_get_public(file_get_contents($this->pubPath));
openssl_public_decrypt(base64_decode($data), $decrypted, $this->pu_key);//公钥解密
return $decrypted;
}
/**
* 私钥加密数据
*/
public function priEncryptKey($data)
{
$this->pi_key = openssl_pkey_get_private(file_get_contents($this->priPath),$this->passphrase);
openssl_private_encrypt($data, $encrypted, $this->pi_key);
return base64_encode($encrypted);
}
/**
* 私钥解密数据
*/
public function priDecodeKey($data)
{
$this->pi_key = openssl_pkey_get_private(file_get_contents($this->priPath),$this->passphrase);
openssl_private_decrypt(base64_decode($data), $decrypted, $this->pi_key);//私钥解密
return $decrypted;
}
}
使用的时候
$Rsa = new RsaClass();
$result = $Rsa->pubEncryptKey(time());
var_dump($result);
$decoded = $Rsa->priDecodeKey($result);
var_dump($decoded);