using System;
using System.Security.Cryptography;
class MainClass {
static void Main() {
var apiKey = "67d594c6-9312-4df8-9b21-952cfdff1617";
var payload = new AuthenticationPayload
{
SourceSystemId = 1,
SourceSystemScenarioId = 1,
ReferenceId = "46436",
Nonce = Guid.NewGuid().ToString()
};
var hashCalc = new HashCalculator();
Console.WriteLine(payload.Nonce);
Console.WriteLine(hashCalc.CalculateHash(apiKey, payload.AsHashAuthenticationString));
}
}
public class AuthenticationPayload
{
public int SourceSystemId { get; set; }
public int SourceSystemScenarioId { get; set; }
public string ReferenceId { get; set; }
public string Nonce { get; set; }
public string AsHashAuthenticationString => $"{SourceSystemId}:{SourceSystemScenarioId}:{ReferenceId}:{Nonce}";
}
public class HashCalculator
{
public string CalculateHash(string key, string computedAuthenticationString)
{
if (string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(computedAuthenticationString))
{
return "";
}
var encoding = new System.Text.UTF8Encoding();
try
{
var keyByte = encoding.GetBytes(key);
var computedAuthenticationBytes = System.Text.Encoding.UTF8.GetBytes(computedAuthenticationString);
var encodedAuthenticationString = Convert.ToBase64String(computedAuthenticationBytes);
var computedHash = "";
using (var hmacsha256 = new HMACSHA256(keyByte))
{
var encodedAuthenticationStringBytes = encoding.GetBytes(encodedAuthenticationString);
var hashmessage = hmacsha256.ComputeHash(encodedAuthenticationStringBytes);
computedHash = ByteToString(hashmessage);
}
return computedHash;
}
catch (Exception ex)
{
return "";
}
}
private string ByteToString(byte[] buff)
{
string sbinary = "";
for (int i = 0; i < buff.Length; i++)
{
sbinary += buff[i].ToString("X2");
}
return (sbinary);
}
}