mark
mark

Reputation: 2063

.Net HMAC and base64 Encoding Issue

I am trying to create a base64-encoded HMAC SHA512 hash using a secret of secret and a payload of foo. I am unable to make my .NET code produce the correct value. I am wondering if the encoding is the underlying issue.

Code:

UTF8Encoding encoding = new UTF8Encoding();
HMACSHA512 hmac = new HMACSHA512(encoding.GetBytes("secret")); // init the HMAC hash with "secret" as a byte array
byte[] hash = hmac.ComputeHash(encoding.GetBytes("foo")); // hash the payload
String result = Convert.ToBase64String(hash); // Base64 encode the payload

The incorrect hash & base64 result:

gt9xA96Ngt5F4BxF/mQrXRPGwrR97K/rwAlDHGZcb6Xz0a9Ol46hvekUJmIgc+vqxho0Ye/UZ+CXHHiLyOvbvg==

The expected hash & base64 result:

ODJkZjcxMDNkZThkODJkZTQ1ZTAxYzQ1ZmU2NDJiNWQxM2M2YzJiNDdkZWNhZmViYzAwOTQzMWM2NjVjNmZhNWYzZDFhZjRlOTc4ZWExYmRlOTE0MjY2MjIwNzNlYmVhYzYxYTM0NjFlZmQ0NjdlMDk3MWM3ODhiYzhlYmRiYmU=

Upvotes: 1

Views: 2111

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

Since second version is just Base64 of Hex representation you need to convert byte array to hex first and than Base64 ASCII version of the string.

Steps:

Upvotes: 2

Related Questions