// // Copyright (c) StellaOps. Licensed under AGPL-3.0-or-later. // using System.Security.Cryptography; namespace StellaOps.Facet; /// /// Default implementation of using .NET built-in algorithms. /// public sealed class DefaultCryptoHash : ICryptoHash { /// /// Gets the singleton instance. /// public static DefaultCryptoHash Instance { get; } = new(); /// 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") }; } /// public async Task 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") }; } }