patbef-ServiceOutside/ServiceShared/Crypto/SHA512.cs

92 lines
2.8 KiB
C#
Raw Normal View History

2024-01-29 16:27:34 +01:00
using System.Security.Cryptography;
using System.Text;
namespace ServiceShared.Crypto
{
public static class SHA512
{
/// <summary>
/// Encrypts a string value in SHA512 hash
/// </summary>
/// <param name="value">string value that should be encrypted in SHA512 hash</param>
/// <returns>Returns SHA512 hash</returns>
public static string Encrypt(string value)
{
string result = null;
try
{
byte[] bytes = Encoding.UTF8.GetBytes(value);
using (System.Security.Cryptography.SHA512 hash = System.Security.Cryptography.SHA512.Create())
{
byte[] hashedInputBytes = hash.ComputeHash(bytes);
StringBuilder hashedInputStringBuilder = new StringBuilder(128);
foreach (var b in hashedInputBytes)
{
hashedInputStringBuilder.Append(b.ToString("X2"));
}
result = hashedInputStringBuilder.ToString().ToLower();
}
}
catch
{
result = null;
}
return result;
}
/// <summary>
/// Generates SHA512 HMAC Hash with key
/// </summary>
/// <param name="message">message that should be signed by sha512 hmac</param>
/// <param name="key">key that should be used for signing</param>
/// <returns>SHA512 HMAC</returns>
public static string HMAC(string message, byte[] key)
{
string result = null;
try
{
StringBuilder hash = new StringBuilder();
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
using (HMACSHA512 hmac = new HMACSHA512(key))
{
byte[] hashValue = hmac.ComputeHash(messageBytes);
foreach (var theByte in hashValue)
{
hash.Append(theByte.ToString("x2"));
}
}
return hash.ToString();
}
catch
{
result = null;
}
return result;
}
/// <summary>
/// Validates HMAC with message and key
/// </summary>
/// <param name="hmac">HMAC from the partner</param>
/// <param name="message">message that should be signed by sha512 hmac</param>
/// <param name="key">key that should be used for signing</param>
/// <returns>returns true if success</returns>
public static bool isValidAuthenticationCode(string hmac, string message, byte[] key)
{
return (hmac != null && HMAC(message, key) == hmac);
}
}
}