修复长数据加密失败的BUG

This commit is contained in:
TOP糯米 2020-10-21 13:20:35 +08:00
parent 57d2a52f03
commit 04f7556475
1 changed files with 28 additions and 7 deletions

View File

@ -10,10 +10,20 @@ namespace encrypt\classes;
class RSA implements \encrypt\RSA
{
/**
* 使用公钥操作
*/
const USE_PUBLIC = 1;
/**
* 使用私钥操作
*/
const USE_PRIVATE = 2;
/**
* 密钥配置
* @var array
*/
private $config = [];
/**
@ -64,9 +74,9 @@ class RSA implements \encrypt\RSA
* @param int $type
* @return null|string
*/
public function encrypt(string $data, $type = RSA::USE_PRIVATE): ?string
public function encrypt(string $data, $type = self::USE_PRIVATE): ?string
{
if (RSA::USE_PRIVATE === $type) {
if (self::USE_PRIVATE === $type) {
$func = 'openssl_private_encrypt';
$key = $this->privateKey();
} else {
@ -74,8 +84,13 @@ class RSA implements \encrypt\RSA
$key = $this->publicKey();
}
$string = '';
foreach (str_split($data, 117) as $chunk) {
/** @var string $encrypted */
return $func($data, $encrypted, $key) ? base64_encode($encrypted) : null;
$string .= ($func($chunk, $encrypted, $key) ? base64_encode($encrypted) : null);
}
return $string;
}
/**
@ -84,9 +99,9 @@ class RSA implements \encrypt\RSA
* @param int $type
* @return null|string
*/
public function decrypt(string $data, $type = RSA::USE_PRIVATE): ?string
public function decrypt(string $data, $type = self::USE_PRIVATE): ?string
{
if (RSA::USE_PRIVATE === $type) {
if (self::USE_PRIVATE === $type) {
$func = 'openssl_private_decrypt';
$key = $this->privateKey();
} else {
@ -94,6 +109,12 @@ class RSA implements \encrypt\RSA
$key = $this->publicKey();
}
return $func(base64_decode($data), $data, $key) ? $data : null;
$string = '';
foreach (str_split($data, 172) as $chunk) {
/** @var string $decryptData */
$string .= ($func(base64_decode($chunk), $decryptData, $key) ? $decryptData : null);
}
return $string;
}
}