You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Payment/UsdtCredentialCipher.php

87 lines
3.0 KiB
PHP

<?php
namespace App\Services\Payment;
use Dotenv\Dotenv;
class UsdtCredentialCipher
{
private const ENV_KEY = 'USDT_CREDENTIAL_KEY';
private const PREFIX = 'sbox:v1:';
public static function encrypt($plainText)
{
$plainText = (string) $plainText;
if ($plainText === '') {
return '';
}
if (!function_exists('sodium_crypto_secretbox')) {
throw new \RuntimeException('PHP sodium 扩展未安装,无法加密 TronGrid API Key');
}
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$cipherText = sodium_crypto_secretbox($plainText, $nonce, self::key());
return self::PREFIX . base64_encode($nonce . $cipherText);
}
public static function decrypt($encoded)
{
$encoded = trim((string) $encoded);
if ($encoded === '') {
return '';
}
if (strpos($encoded, self::PREFIX) !== 0) {
throw new \RuntimeException('TronGrid API Key 不是受支持的加密格式,请在后台重新保存');
}
if (!function_exists('sodium_crypto_secretbox_open')) {
throw new \RuntimeException('PHP sodium 扩展未安装,无法解密 TronGrid API Key');
}
$payload = base64_decode(substr($encoded, strlen(self::PREFIX)), true);
if ($payload === false || strlen($payload) <= SODIUM_CRYPTO_SECRETBOX_NONCEBYTES) {
throw new \RuntimeException('TronGrid API Key 密文格式无效');
}
$nonce = substr($payload, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$cipherText = substr($payload, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$plainText = sodium_crypto_secretbox_open($cipherText, $nonce, self::key());
if ($plainText === false) {
throw new \RuntimeException('TronGrid API Key 解密失败,请检查 USDT_CREDENTIAL_KEY');
}
return $plainText;
}
private static function key()
{
$raw = self::environmentKey();
if ($raw === '' && defined('BASE_PATH')) {
try {
Dotenv::createImmutable(BASE_PATH)->safeLoad();
} catch (\Throwable $exception) {
// The validation error below identifies the missing setting.
}
$raw = self::environmentKey();
}
if ($raw === '') {
throw new \RuntimeException('未配置环境变量 USDT_CREDENTIAL_KEY');
}
$decoded = base64_decode($raw, true);
if ($decoded !== false && strlen($decoded) === SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
return $decoded;
}
if (preg_match('/^[a-f0-9]{64}$/i', $raw)) {
return hex2bin($raw);
}
throw new \RuntimeException('USDT_CREDENTIAL_KEY 必须是 32 字节 Base64 或 64 位十六进制字符串');
}
private static function environmentKey()
{
$raw = trim((string) getenv(self::ENV_KEY));
if ($raw === '' && isset($_ENV[self::ENV_KEY])) {
$raw = trim((string) $_ENV[self::ENV_KEY]);
}
return $raw;
}
}