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/Cloud/CloudSecrets.php

58 lines
2.3 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Services\Config;
final class CloudSecrets
{
public static function key(string $purpose): string
{
$setting = $purpose === 'payload_key' ? 'cloud_payload_key' : 'cloud_engine_hmac_key';
$fileSetting = $purpose === 'payload_key' ? 'cloud_payload_key_file' : 'cloud_engine_hmac_file';
$value = trim((string) Config::get($setting, ''));
if ($value === '') {
$path = (string) Config::get($fileSetting, '');
if ($path === '' || !is_file($path) || !is_readable($path)) {
throw new CloudError('虚拟化服务密钥尚未配置', 503);
}
$value = trim((string) file_get_contents($path));
}
$key = base64_decode($value, true);
if ($key === false || strlen($key) !== 32) {
throw new CloudError('虚拟化服务密钥格式无效', 503);
}
return $key;
}
public static function encrypt(array $payload): string
{
if (!function_exists('sodium_crypto_secretbox')) {
throw new CloudError('需要 PHP sodium 扩展', 503);
}
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$raw = json_encode($payload, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
return base64_encode($nonce . sodium_crypto_secretbox($raw, $nonce, self::key('payload_key')));
}
public static function decrypt(string $ciphertext): array
{
if (!function_exists('sodium_crypto_secretbox_open')) {
throw new CloudError('需要 PHP sodium 扩展', 503);
}
$raw = base64_decode($ciphertext, true);
if ($raw === false || strlen($raw) < SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES) {
throw new CloudError('任务数据无法解密', 503);
}
$plain = sodium_crypto_secretbox_open(substr($raw, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES),
substr($raw, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES), self::key('payload_key'));
if ($plain === false) {
throw new CloudError('任务数据无法解密', 503);
}
$value = json_decode($plain, true, 32, JSON_THROW_ON_ERROR);
if (!is_array($value)) {
throw new CloudError('任务数据格式无效', 503);
}
return $value;
}
}