Files
nl-admin-api/app/Service/common/FieldEncryptService.php

73 lines
2.0 KiB
PHP
Raw Normal View History

2026-08-10 15:51:00 +08:00
<?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);
}
}