73 lines
2.0 KiB
PHP
73 lines
2.0 KiB
PHP
<?php
|
||
|
||
namespace App\Service\common;
|
||
|
||
use App\BaseApp\BaseNotAuthService;
|
||
use App\Core\DatabaseEncryptor;
|
||
|
||
/**
|
||
* 库内敏感字段加解密服务(API Key 等)
|
||
* 入库写 nl_ase_256_;读取兼容历史 ***
|
||
*/
|
||
class FieldEncryptService extends BaseNotAuthService
|
||
{
|
||
private ?DatabaseEncryptor $encryptor = null;
|
||
|
||
/**
|
||
* 获取加解密器(懒加载,密钥来自 config/nl.php)
|
||
*/
|
||
private function encryptor(): DatabaseEncryptor
|
||
{
|
||
if ($this->encryptor === null) {
|
||
$key = (string) config('nl.encrypt_key', '');
|
||
if ($key === '') {
|
||
$this->utils->errorThrow('未配置 ENCRYPT_KEY,无法加解密敏感字段');
|
||
}
|
||
$this->encryptor = new DatabaseEncryptor($key);
|
||
}
|
||
return $this->encryptor;
|
||
}
|
||
|
||
/**
|
||
* 入库前加密:明文 → nl_ase_256_...
|
||
*
|
||
* @param string|null $plain 明文
|
||
*/
|
||
public function encryptForStorage(?string $plain): string
|
||
{
|
||
try {
|
||
return $this->encryptor()->encrypt($plain);
|
||
} catch (\Throwable $e) {
|
||
$this->utils->errorThrow('敏感字段加密失败:' . $e->getMessage());
|
||
}
|
||
return '';
|
||
}
|
||
|
||
/**
|
||
* 读取后解密:nl_ase_256_ / 历史 *** → 明文
|
||
*
|
||
* @param string|null $cipher 库内值
|
||
* @param bool $silentFail true 时解密失败返回空串;false 抛业务异常
|
||
*/
|
||
public function decryptFromStorage(?string $cipher, bool $silentFail = false): string
|
||
{
|
||
try {
|
||
return $this->encryptor()->decrypt($cipher);
|
||
} catch (\Throwable $e) {
|
||
if ($silentFail) {
|
||
return '';
|
||
}
|
||
$this->utils->errorThrow('敏感字段解密失败:' . $e->getMessage());
|
||
}
|
||
return '';
|
||
}
|
||
|
||
/**
|
||
* 是否已是库内密文
|
||
*/
|
||
public function isEncrypted(?string $value): bool
|
||
{
|
||
return DatabaseEncryptor::isEncrypted($value);
|
||
}
|
||
}
|