Files
git.stella-ops.org/src/__Libraries/StellaOps.Cryptography.Providers.OfflineVerification/OfflineVerificationCryptoProvider.Signing.cs

81 lines
2.8 KiB
C#

using StellaOps.Cryptography;
using System;
using System.Collections.Generic;
using System.Linq;
namespace StellaOps.Cryptography.Providers.OfflineVerification;
public sealed partial class OfflineVerificationCryptoProvider
{
/// <summary>
/// Gets a signer for the specified algorithm and key.
/// </summary>
/// <param name="algorithmId">The signing algorithm identifier.</param>
/// <param name="keyReference">The key reference.</param>
/// <returns>An instance of <see cref="ICryptoSigner"/>.</returns>
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);
}
/// <summary>
/// Upserts a signing key into the provider.
/// </summary>
/// <param name="signingKey">The signing key to add or update.</param>
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);
}
/// <summary>
/// Removes a signing key from the provider.
/// </summary>
/// <param name="keyId">The key identifier to remove.</param>
/// <returns>True if the key was removed; otherwise, false.</returns>
public bool RemoveSigningKey(string keyId)
{
if (string.IsNullOrWhiteSpace(keyId))
{
return false;
}
return _signingKeys.TryRemove(keyId, out _);
}
/// <summary>
/// Gets all signing keys stored in the provider.
/// </summary>
/// <returns>A read-only collection of signing keys.</returns>
public IReadOnlyCollection<CryptoSigningKey> GetSigningKeys()
=> _signingKeys.Values.ToArray();
}