更新RSA加密类

This commit is contained in:
TOP糯米 2020-10-21 11:38:52 +08:00
parent db289d2e58
commit 57d2a52f03
2 changed files with 96 additions and 5 deletions

View File

@ -4,11 +4,11 @@ namespace encrypt;
interface RSA
{
public function publicKey(): string;
public function publicKey();
public function privateKey(): string;
public function privateKey();
public function encrypt(string $data, bool $public = true): string;
public function encrypt(string $data): ?string;
public function decrypt(string $data, bool $public = true): string;
public function decrypt(string $data): ?string;
}

View File

@ -2,7 +2,98 @@
namespace encrypt\classes;
/**
* RSA加密解密类
* Class RSA
* @package encrypt\classes
*/
class RSA implements \encrypt\RSA
{
const USE_PUBLIC = 1;
const USE_PRIVATE = 2;
private $config = [];
/**
* RSA constructor.
* @param array $config
*
* $config = ['public_key' => 'path', 'private_key' => 'path']
*
* @throws \Exception
*/
public function __construct(array $config)
{
$this->config = $config;
if (!isset($this->config['public_key'], $this->config['private_key'])) {
throw new \Exception('公钥私钥参数错误');
}
}
/**
* 获取公钥
* @return string
*/
public function publicKey()
{
if (!is_file($this->config['public_key'])) {
return '';
}
$content = file_get_contents($this->config['public_key']);
return openssl_pkey_get_public($content);
}
/**
* 获取私钥
* @return string
*/
public function privateKey()
{
if (!is_file($this->config['private_key'])) {
return '';
}
$content = file_get_contents($this->config['private_key']);
return openssl_pkey_get_private($content);
}
/**
* 加密数据
* @param string $data
* @param int $type
* @return null|string
*/
public function encrypt(string $data, $type = RSA::USE_PRIVATE): ?string
{
if (RSA::USE_PRIVATE === $type) {
$func = 'openssl_private_encrypt';
$key = $this->privateKey();
} else {
$func = 'openssl_public_encrypt';
$key = $this->publicKey();
}
/** @var string $encrypted */
return $func($data, $encrypted, $key) ? base64_encode($encrypted) : null;
}
/**
* 解密数据
* @param string $data
* @param int $type
* @return null|string
*/
public function decrypt(string $data, $type = RSA::USE_PRIVATE): ?string
{
if (RSA::USE_PRIVATE === $type) {
$func = 'openssl_private_decrypt';
$key = $this->privateKey();
} else {
$func = 'openssl_public_decrypt';
$key = $this->publicKey();
}
return $func(base64_decode($data), $data, $key) ? $data : null;
}
}