Files
git.stella-ops.org/src/__Libraries/StellaOps.Facet/DefaultCryptoHash.cs
StellaOps Bot 37e11918e0 save progress
2026-01-06 09:42:20 +02:00

54 lines
1.8 KiB
C#

// <copyright file="DefaultCryptoHash.cs" company="StellaOps">
// Copyright (c) StellaOps. Licensed under AGPL-3.0-or-later.
// </copyright>
using System.Security.Cryptography;
namespace StellaOps.Facet;
/// <summary>
/// Default implementation of <see cref="ICryptoHash"/> using .NET built-in algorithms.
/// </summary>
public sealed class DefaultCryptoHash : ICryptoHash
{
/// <summary>
/// Gets the singleton instance.
/// </summary>
public static DefaultCryptoHash Instance { get; } = new();
/// <inheritdoc/>
public byte[] ComputeHash(byte[] data, string algorithm)
{
ArgumentNullException.ThrowIfNull(data);
ArgumentException.ThrowIfNullOrWhiteSpace(algorithm);
return algorithm.ToUpperInvariant() switch
{
"SHA256" => SHA256.HashData(data),
"SHA384" => SHA384.HashData(data),
"SHA512" => SHA512.HashData(data),
"SHA1" => SHA1.HashData(data),
"MD5" => MD5.HashData(data),
_ => throw new NotSupportedException($"Hash algorithm '{algorithm}' is not supported")
};
}
/// <inheritdoc/>
public async Task<byte[]> ComputeHashAsync(
Stream stream,
string algorithm,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(stream);
ArgumentException.ThrowIfNullOrWhiteSpace(algorithm);
return algorithm.ToUpperInvariant() switch
{
"SHA256" => await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false),
"SHA384" => await SHA384.HashDataAsync(stream, ct).ConfigureAwait(false),
"SHA512" => await SHA512.HashDataAsync(stream, ct).ConfigureAwait(false),
_ => throw new NotSupportedException($"Hash algorithm '{algorithm}' is not supported for async")
};
}
}