using StellaOps.Cryptography;
using System;
using System.Collections.Generic;
using System.Linq;
namespace StellaOps.Cryptography.Providers.OfflineVerification;
public sealed partial class OfflineVerificationCryptoProvider
{
///
/// Gets a signer for the specified algorithm and key.
///
/// The signing algorithm identifier.
/// The key reference.
/// An instance of .
public ICryptoSigner GetSigner(string algorithmId, CryptoKeyReference keyReference)
{
ArgumentNullException.ThrowIfNull(keyReference);
var normalizedAlg = NormalizeAlgorithm(algorithmId);
if (!IsSupportedSigningAlgorithm(normalizedAlg))
{
throw new InvalidOperationException($"Signing algorithm '{algorithmId}' is not supported by provider '{Name}'.");
}
if (!_signingKeys.TryGetValue(keyReference.KeyId, out var signingKey))
{
throw new KeyNotFoundException($"Signing key '{keyReference.KeyId}' is not registered with provider '{Name}'.");
}
if (!string.Equals(signingKey.AlgorithmId, normalizedAlg, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(
$"Signing key '{keyReference.KeyId}' is registered for algorithm '{signingKey.AlgorithmId}', not '{algorithmId}'.");
}
return EcdsaSigner.Create(signingKey);
}
///
/// Upserts a signing key into the provider.
///
/// The signing key to add or update.
public void UpsertSigningKey(CryptoSigningKey signingKey)
{
ArgumentNullException.ThrowIfNull(signingKey);
var normalizedAlg = NormalizeAlgorithm(signingKey.AlgorithmId);
if (!IsSupportedSigningAlgorithm(normalizedAlg))
{
throw new InvalidOperationException($"Signing algorithm '{signingKey.AlgorithmId}' is not supported by provider '{Name}'.");
}
_signingKeys.AddOrUpdate(signingKey.Reference.KeyId, signingKey, (_, _) => signingKey);
}
///
/// Removes a signing key from the provider.
///
/// The key identifier to remove.
/// True if the key was removed; otherwise, false.
public bool RemoveSigningKey(string keyId)
{
if (string.IsNullOrWhiteSpace(keyId))
{
return false;
}
return _signingKeys.TryRemove(keyId, out _);
}
///
/// Gets all signing keys stored in the provider.
///
/// A read-only collection of signing keys.
public IReadOnlyCollection GetSigningKeys()
=> _signingKeys.Values.ToArray();
}