From 219c179a83abfa839f59115d60b59e4fdcb30ecf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?TOP=E7=B3=AF=E7=B1=B3?= <1130395124@qq.com> Date: Wed, 21 Oct 2020 18:36:02 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0RSA=E9=83=A8=E5=88=86?= =?UTF-8?q?=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/RSA.php | 4 ++-- src/classes/RSA.php | 24 +++++++++++++----------- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/src/RSA.php b/src/RSA.php index ee2251a..adf3317 100644 --- a/src/RSA.php +++ b/src/RSA.php @@ -8,7 +8,7 @@ interface RSA public function privateKey(); - public function encrypt(string $data): ?string; + public function encrypt(string $data): string; - public function decrypt(string $data): ?string; + public function decrypt(string $data): string; } diff --git a/src/classes/RSA.php b/src/classes/RSA.php index cac09ae..5b41e8c 100644 --- a/src/classes/RSA.php +++ b/src/classes/RSA.php @@ -38,33 +38,35 @@ class RSA implements \encrypt\RSA { $this->config = $config; if (!isset($this->config['public_key'], $this->config['private_key'])) { - throw new \Exception('公钥私钥参数错误'); + throw new \Exception('密钥参数错误'); } } /** * 获取公钥 - * @return string + * @return null|resource */ public function publicKey() { if (!is_file($this->config['public_key'])) { - return ''; + return null; } $content = file_get_contents($this->config['public_key']); + return openssl_pkey_get_public($content); } /** * 获取私钥 - * @return string + * @return null|resource */ public function privateKey() { if (!is_file($this->config['private_key'])) { - return ''; + return null; } $content = file_get_contents($this->config['private_key']); + return openssl_pkey_get_private($content); } @@ -72,9 +74,9 @@ class RSA implements \encrypt\RSA * 加密数据 * @param string $data * @param int $type - * @return null|string + * @return string */ - public function encrypt(string $data, $type = self::USE_PRIVATE): ?string + public function encrypt(string $data, int $type = self::USE_PRIVATE): string { if (self::USE_PRIVATE === $type) { $func = 'openssl_private_encrypt'; @@ -86,8 +88,8 @@ class RSA implements \encrypt\RSA $string = ''; foreach (str_split($data, 117) as $chunk) { - /** @var string $encrypted */ - $string .= ($func($chunk, $encrypted, $key) ? base64_encode($encrypted) : null); + /** @var string $encryptData */ + $string .= ($func($chunk, $encryptData, $key) ? base64_encode($encryptData) : null); } return $string; @@ -97,9 +99,9 @@ class RSA implements \encrypt\RSA * 解密数据 * @param string $data * @param int $type - * @return null|string + * @return string */ - public function decrypt(string $data, $type = self::USE_PRIVATE): ?string + public function decrypt(string $data, int $type = self::USE_PRIVATE): string { if (self::USE_PRIVATE === $type) { $func = 'openssl_private_decrypt';