RSA加密
前情提要
随着网络的发展,互联网公司对于数据的保护也越来越加的严格了,众所周知最长用的两个加密算法,就是 对称加密与非对称加密了。至于这俩个算法的相关知识,大家可以自行去了解,今天着重实战RSA实现对称算法。
编写RSA密钥生成器
<?php
class KeyGenerator
{
// 新的私钥
protected $res;
// 密钥key
private $privateKey;
// 公钥key
private $publicKey;
/**
* 创建密钥的配置
* @var array
*/
protected static $config = [
"digest_alg" => "sha512", // 文摘
"private_key_bits" => 4096, // 私钥位 字节数
"private_key_type" => OPENSSL_KEYTYPE_RSA, // 加密密钥类型
"config" => "/etc/ssl/openssl.cnf"
];
/**
* 初始化时 生成一个新的私钥
* @throws Exception
*/
public function __construct()
{
$this->res = openssl_pkey_new($this->config);
if (empty($this->res)) {
throw new Exception('生成密钥失败');
}
}
/**
* 生成密钥
* @throws Exception
*/
protected function generatePrivateKey()
{
openssl_pkey_export($this->res,$this->privateKey , null, self::$config);
if (empty($this->privateKey)) {
throw new Exception('生成私钥失败');
}
}
/**
* @throws Exception
*/
protected function generatePublicKey()
{
$publicKey = openssl_pkey_get_details($this->res);
if (empty($publicKey['key'])) {
throw new Exception('生成公钥失败');
}
$this->publicKey = $publicKey['key'];
}
/**
* 生成公钥与密钥文件
* @throws Exception
*/
public function generate()
{
$this->generatePublicKey();
$this->generatePrivateKey();
file_put_contents("./public_test.pem", $this->publicKey);
file_put_contents("./private_test.pem", $this->privateKey);
openssl_free_key($this->res);
}
}
加密解密实例
<?php
class Openssl
{
/**
* 公钥加密
* @param array $data
* @param string $publicKeyFile
* @return mixed
* @throws Exception
*/
public function encrypt(array $data, string $publicKeyFile)
{
$filePath = __DIR__.'/'.$publicKeyFile;
if (!file_exists($filePath)) {
throw new Exception('公钥文件没有找到');
}
$publicKey = file_get_contents($filePath);
openssl_public_encrypt(json_encode($data), $encrypted, $publicKey);
return $encrypted;
}
/**
* 公钥解密
* @param string $encrypted
* @param string $privateKeyFile
* @throws Exception
*/
public function decrypt(string $encrypted, string $privateKeyFile)
{
$filePath = __DIR__.'/'.$privateKeyFile;
if (!file_exists($filePath)) {
throw new Exception('私钥文件没有找到');
}
$privateKey = file_get_contents($privateKeyFile);
openssl_private_decrypt($encrypted, $decrypted, $privateKey);
}
}
总结
在使用此算法时,我们需要着重注意对公钥私钥的保存与管理。如果是在对外的接口时,就需要不同公钥私钥去进行处理。下一章我将会对加密算法摘要做出处理。