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

58 lines
2.1 KiB
C#

using System.Text;
using MfGames.Cryptography.Hashes;
namespace MfGames.Cryptography.Extensions;
/// <summary>
/// Extension methods for generating hashes for strings.
/// </summary>
public static class CryptographyStringExtensions
{
/// <summary>
/// Gets the encoded byte array of the given string.
/// </summary>
/// <param name="input">The input string or null.</param>
/// <param name="encoding">The encoding to use, defaults to UTF-8.</param>
/// <returns>Null if the input was null, otherwise the byte array.</returns>
public static byte[]? ToBytes(this string? input, Encoding? encoding = null)
{
encoding ??= Encoding.UTF8;
return input == null ? null : encoding.GetBytes(input);
}
/// <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>
/// <param name="encoding">The encoding to use, defaults to UTF-8.</param>
/// <returns>Null if input is null, otherwise the hash value.</returns>
public static byte[]? ToHashBytes(
this string? input,
HashType hash = HashType.Sha512,
Encoding? encoding = null
)
{
return input == null ? null : hash.CreateHash().ComputeHash(input.ToBytes(encoding)!);
}
/// <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>
/// <param name="encoding">The encoding to use, defaults to UTF-8.</param>
/// <returns>Null if input is null, otherwise the hash value.</returns>
public static string? ToHashString(
this string? input,
HashType hash = HashType.Sha512,
ByteStringFormat format = ByteStringFormat.LowercaseHex,
Encoding? encoding = null
)
{
return input?.ToHashBytes(hash, encoding)?.ToByteString(format);
}
}