mfgames-cil/src/MfGames.Cryptography/Extensions/CryptoByteArrayExtensions.cs

69 lines
2.1 KiB
C#

using MfGames.Crypto.Hashes;
namespace MfGames.Crypto.Extensions;
/// <summary>
/// Extension methods on byte arrays.
/// </summary>
public static class CryptoByteArrayExtensions
{
/// <summary>
/// Converts the input into a hash string, such as hex or base64.
/// </summary>
/// <param name="input"></param>
/// <param name="format"></param>
/// <returns></returns>
public static string? ToByteString(
this byte[]? input,
ByteStringFormat format = ByteStringFormat.LowercaseHex
)
{
if (input == null)
{
return null;
}
switch (format)
{
case ByteStringFormat.LowercaseHex:
return Convert.ToHexString(input).ToLowerInvariant();
case ByteStringFormat.UppercaseHex:
return Convert.ToHexString(input);
case ByteStringFormat.Base64:
return Convert.ToBase64String(input);
default:
throw new ArgumentOutOfRangeException(nameof(format), format, null);
}
}
/// <summary>
/// Hashes the given input and returns the results.
/// </summary>
/// <param name="input">A byte array or null.</param>
/// <param name="hash">The type of hash requested.</param>
/// <returns>Null if input is null, otherwise the hash value.</returns>
public static byte[]? ToHashBytes(this byte[]? input, HashType hash = HashType.Sha512)
{
return input == null ? null : hash.CreateHash().ComputeHash(input);
}
/// <summary>
/// Hashes the given input and returns the results as a string.
/// </summary>
/// <param name="input">A byte array or null.</param>
/// <param name="hash">The type of hash requested.</param>
/// <param name="format">The format of the requested string.</param>
/// <returns>Null if input is null, otherwise the hash value.</returns>
public static string? ToHashString(
this byte[]? input,
HashType hash = HashType.Sha512,
ByteStringFormat format = ByteStringFormat.LowercaseHex
)
{
return input?.ToHashBytes(hash)?.ToByteString(format);
}
}