using System.Collections.Generic;
using System.Security.Cryptography;
public static void Main()
var signablerequest = FormatRequest();
var hmacSignature = GenerateHmacSignature("e914a17c10c8b9fc892c4b5f9343da08f3d62f6f7023e85d7ecf6c6324cfa278", signablerequest, null, null);
Console.WriteLine(signablerequest);
Console.WriteLine(hmacSignature);
public static string FormatRequest()
dynamic request = new ExpandoObject();
request.nonce = "f7360a0e-e39e-4049-bef5-53fbacf8c8dd";
request.epochUtcTime = null;
request.RequestedAmount = "1000";
request.SecureCoAccountId = "cli20p51qqbp";
request.RequestType = "semafone";
request.OrderNumber = "123";
request.FirstName = "Test";
request.LastName = "User";
request.RequestID = "738126f1-7eca-409d-be96-119f26831a6c";
request.TransactionType = "purchase";
request.SemafoneCrn = null;
request.SemafoneSessionID = null;
request.SemafoneEndpoint = null;
request.BearerToken = "2cba1b8040e09040d7730f16a7851b3f";
request.Token = "token_from_Yaml";
request.AgentID = "Agent Fred";
StringBuilder signableRequest = new StringBuilder();
foreach (var property in (IDictionary<String, Object>)request)
signableRequest.Append(property.Key + "=" + property.Value).Append("&");
return signableRequest.ToString().TrimEnd(new char[] { '&' });
public static string GenerateHmacSignature(string hexKey, string message, string epochUtcTime = null, string nonce = null)
if (String.IsNullOrEmpty(hexKey))
throw new Exception("HexKey is null or Empty.");
if (!IsValidHexString(hexKey))
throw new Exception("HexKey contains non-hexidecimal characters.");
byte[] byteKey = HexStringToByteArray(hexKey);
if (byteKey.Length != 32 && byteKey.Length != 64)
throw new Exception("Key length is not 256 or 512 bits");
var completeMessage = message;
using (HMACSHA256 hmac = new HMACSHA256(byteKey))
using (MemoryStream inStream = new MemoryStream(Encoding.UTF8.GetBytes(completeMessage)))
hashValue = hmac.ComputeHash(inStream);
return ByteArrayToHexString(hashValue);
public static byte[] HexStringToByteArray(String hex)
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
public static string ByteArrayToHexString(byte[] ba)
StringBuilder hex = new StringBuilder(ba.Length * 2);
hex.AppendFormat("{0:x2}", b);
private static bool IsValidHexString(IEnumerable<char> hexString)
return hexString.Select(currentCharacter =>
(currentCharacter >= '0' && currentCharacter <= '9') ||
(currentCharacter >= 'a' && currentCharacter <= 'f') ||
(currentCharacter >= 'A' && currentCharacter <= 'F')).All(isHexCharacter => isHexCharacter);