function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Kimberly SullivanKimberly Sullivan 

How to create a HmacSHA256 hash to match C# external service

I'm trying to create a HmacSHA256 hash that will return the same value as my C# external service hash.
Currently I cannot get them to match, can someone see where I'm going wrong?

public String CreateToken(string jsonData, Datetime timestamp, String transactionKey)
		String algorithmName = 'HmacSHA256';
		Long epochTime = timestamp.getTime()/1000;
		String payload = jsonData + '^' + epochTime;

		System.debug('algorithmName: ' + algorithmName);
		System.debug('Datetime: ' + epochTime);
		System.debug('payload: ' + payload);

		Blob token = Crypto.generateMac(algorithmName, blob.valueOf(payload), blob.valueOf(transactionKey));

		return (EncodingUtil.convertToHex(token)).replace('-','').toLowerCase();

C# Code
private static string ComputeHash(string jsonData, DateTime timestamp, string trasactionKey)
            var key = Encoding.UTF8.GetBytes(trasactionKey);
            var payload = Encoding.UTF8.GetBytes(string.Format("{0}^{1}", jsonData, ToUnixTime(timestamp)));
            using (var hmacSHA = new HMACSHA256(key))
                var hash = hmacSHA.ComputeHash(payload, 0, payload.Length);
                return BitConverter.ToString(hash).Replace("-", "").ToLower();

I have got the timestamps to match.

Any help is greatly appreciated. Thanks!
When I have done this in the past I've had to use ascii.getBytes() in C# instead of UTF8.   You can see this post [1] for the Salesforce and C# usage of the HMAC utilities.