save progress
This commit is contained in:
53
src/__Libraries/StellaOps.Facet/DefaultCryptoHash.cs
Normal file
53
src/__Libraries/StellaOps.Facet/DefaultCryptoHash.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
// <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")
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user