You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.3 KiB
49 lines
1.3 KiB
3 weeks ago
|
<?php
|
||
|
|
||
|
declare(strict_types=1);
|
||
|
|
||
|
namespace App\Utils\Traits;
|
||
|
trait UniversalEncryption
|
||
|
{
|
||
|
private string $key;
|
||
|
|
||
|
public function getKey(): string
|
||
|
{
|
||
|
$key = openssl_digest(env('UNIVERSAL_ENCRYPTION_AES_KEY'), 'sha256', true);
|
||
|
return hash_pbkdf2('sha256', $key, '', 1, 32, true);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Encrypt
|
||
|
* @param string $data
|
||
|
* @return string
|
||
|
*/
|
||
|
public function encrypt(string $data): string
|
||
|
{
|
||
|
$ivSize = openssl_cipher_iv_length('aes-256-cbc'); // AES-256-CBC需要的IV长度
|
||
|
$iv = openssl_random_pseudo_bytes($ivSize); // 生成随机的IV
|
||
|
|
||
|
$encrypted = openssl_encrypt($data, 'aes-256-cbc', $this->getKey(), OPENSSL_RAW_DATA, $iv);
|
||
|
|
||
|
$encryptedWithIv = $iv . $encrypted;
|
||
|
|
||
|
return base64_encode($encryptedWithIv);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Decrypt
|
||
|
* @param string $encryptedData
|
||
|
* @return bool|string
|
||
|
*/
|
||
|
public function decrypt(string $encryptedData): bool|string
|
||
|
{
|
||
|
$encodedData = base64_decode($encryptedData);
|
||
|
|
||
|
$ivSize = openssl_cipher_iv_length('aes-256-cbc');
|
||
|
$iv = mb_substr($encodedData, 0, $ivSize, '8bit');
|
||
|
$encryptedData = mb_substr($encodedData, $ivSize, null, '8bit');
|
||
|
|
||
|
return openssl_decrypt($encryptedData, 'aes-256-cbc', $this->getKey(), OPENSSL_RAW_DATA, $iv);
|
||
|
}
|
||
|
}
|