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/CloudSSHKeys.php

45 lines
1.6 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudSSHKey;
final class CloudSSHKeys
{
public static function parse(string $publicKey): array
{
$parts = preg_split('/\s+/', trim($publicKey), 3);
$type = $parts[0] ?? '';
if (!in_array($type, ['ssh-ed25519', 'ssh-rsa', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp521'], true)
|| strlen($publicKey) > 16384
|| preg_match('/[\x00-\x1f\x7f]/', $publicKey) === 1) {
throw new CloudError('请输入单行 OpenSSH 公钥,不是私钥');
}
$raw = base64_decode($parts[1] ?? '', true);
if ($raw === false || strlen($raw) < 4) {
throw new CloudError('SSH 公钥格式无效');
}
$size = unpack('N', substr($raw, 0, 4))[1];
if ($size !== strlen($type) || substr($raw, 4, $size) !== $type || strlen($raw) <= 4 + $size) {
throw new CloudError('SSH 公钥格式无效');
}
return ['public_key' => $type . ' ' . base64_encode($raw),
'fingerprint' => 'SHA256:' . rtrim(base64_encode(hash('sha256', $raw, true)), '=')];
}
public static function owned($keyId, int $owner): ?CloudSSHKey
{
if ($keyId === null || $keyId === '') {
return null;
}
$id = filter_var($keyId, FILTER_VALIDATE_INT);
if ($id === false || $id < 1) {
throw new CloudError('SSH 公钥不存在', 404);
}
$key = CloudSSHKey::where('id', $id)->where('user_id', $owner)->first();
if ($key === null) {
throw new CloudError('SSH 公钥不存在', 404);
}
return $key;
}
}