2

I need c# equivalent of the below nodejs code. I have some c# code, but the results are not the same.

//working node code below

    Ice3x.prototype._signMessage = function (message) {
  var hmac = crypto.createHmac('sha512',new Buffer(this.secret, 'base64'));
  hmac.update(message);
  var signature = hmac.digest('base64');
  return signature;
}

//c# code below

   public class HmacSignatureCalculator : ICalculteSignature
    {
        public string Signature(string secret, string value)
        {
            var secretBytes = Encoding.UTF8.GetBytes(secret);
            var valueBytes = Encoding.UTF8.GetBytes(value);
            string signature;

            using (var hmac = new HMACSHA512(secretBytes))
            {
                var hash = hmac.ComputeHash(valueBytes);
                signature = Convert.ToBase64String(hash);
            }
            return signature;
        }
    }

1 Answer 1

3

It looks like the difference comes from the way the secret is encoded. In the node version it assumes that it represents a base64 encoded byte array, whereas in your C# version you treat it as a normal string.

So in your C# version read the byte array from the base 64 encoded secret:

var secretBytes = Convert.FromBase64String(secret);

Now you are consistent with the node version:

var hmac = crypto.createHmac('sha512', new Buffer(this.secret, 'base64'));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks .. just to add.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.