90 lines
2.5 KiB
PHP
90 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Services;
|
|
|
|
class SignRSA
|
|
{
|
|
protected string $key;
|
|
protected ?string $private;
|
|
protected string $public;
|
|
protected ?string $previousKey;
|
|
protected ?string $previousPublic;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->key = base64_decode(config('rsa.key'));
|
|
$this->private = str_replace('\n', "\n", config('rsa.private'));
|
|
$this->public = str_replace('\n', "\n", config('rsa.public'));
|
|
$this->previousKey = config('rsa.previous_key') ? base64_decode(config('rsa.previous_key')) : null;
|
|
$this->previousPublic = config('rsa.previous_public') ? str_replace('\n', "\n", config('rsa.previous_public')) : null;
|
|
}
|
|
|
|
|
|
public function EncryptFunc($signdata): string
|
|
{
|
|
|
|
$sign = $this->SignData($signdata);
|
|
|
|
return $this->EncryptedData($signdata . '|' . $sign, $this->key);
|
|
}
|
|
|
|
private function SignData($signdata = ''): string
|
|
{
|
|
|
|
openssl_sign($signdata, $result, $this->private, 'sha256WithRSAEncryption');
|
|
|
|
return base64_encode($result);
|
|
}
|
|
|
|
private function EncryptedData($original_schema = '', $key_hash = ''): string
|
|
{
|
|
$encrypted_data = openssl_encrypt($original_schema, 'DES-EDE3', $key_hash, OPENSSL_RAW_DATA);
|
|
|
|
return base64_encode($encrypted_data);
|
|
}
|
|
|
|
/*
|
|
* Function Decrypt Data
|
|
*/
|
|
|
|
public function DecryptFunc($data): string
|
|
{
|
|
if (!$data) {
|
|
return false;
|
|
}
|
|
$encrypted_data = base64_decode($data);
|
|
$verified = $this->Verify_Sign((string) $this->DecryptData($encrypted_data, $this->key), $this->public);
|
|
|
|
if ($verified === false && $this->previousKey && $this->previousPublic) {
|
|
$verified = $this->Verify_Sign((string) $this->DecryptData($encrypted_data, $this->previousKey), $this->previousPublic);
|
|
}
|
|
|
|
return $verified;
|
|
}
|
|
|
|
private function DecryptData($encrypted_data, $random_key): bool|string
|
|
{
|
|
return openssl_decrypt($encrypted_data, 'DES-EDE3', $random_key, OPENSSL_RAW_DATA);
|
|
}
|
|
|
|
private function Verify_Sign(string $decrypted_data, string $public): string|false
|
|
{
|
|
$data_arr = explode('|', $decrypted_data);
|
|
|
|
if (!isset($data_arr[1])) {
|
|
return false;
|
|
}
|
|
|
|
$signature = base64_decode($data_arr[1]);
|
|
|
|
unset($data_arr[1]);
|
|
|
|
$signature_data = implode('|', $data_arr);
|
|
|
|
$verify = openssl_verify($signature_data, $signature, $public, 'sha256WithRSAEncryption');
|
|
|
|
return $verify === 1 ? $signature_data : false;
|
|
}
|
|
|
|
}
|