Reputation: 1
tldr: I don't think this is a duplicated. I've read many of this questions, and most of them focus on the string to bytes side of the problem. Here I already got identical bytes array. In which case, I want to know WHY I don't get the same results if I have the same bytes.
I'm trying to encode some message with c# and HMACSHA1 algorithm so I can add an authenticate header to consume an api. I am doing this with a secret key I received from the API provider. I got a php and a java implementation which are working to generate the needed hash, but haven't been able to replicate it in c#. Since I think I have narrowed down the difference in java, I'm showing that implementation (since java and c# both have to go through bytes, I think I can explain my question better).
Bellow, I show snippets of code that explain how I'm hashing in both languages, and the result of the bytes array I believe should be the same.
byte[] keyBytes = Encoding.ASCII.GetBytes(secret);
byte[] dataBytes = Encoding.ASCII.GetBytes(input);
using (HMACSHA1 sha1 = new HMACSHA1(keyBytes, true))
{
sha1.Initialize();
byte[] hash = sha1.ComputeHash(dataBytes);
// hash: [245, 46, 78, ...]
}
I'm trying to do the same in java, and I have the following code
byte[] keyBytes = key.getBytes();
byte[] dataBytes = data.getBytes();
String hmacSHA1 = "HmacSHA1";
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, hmacSHA1);
Mac mac = Mac.getInstance(hmacSHA1);
mac.init(signingKey);
byte[] hashed = mac.doFinal(dataBytes);
// hash: [117, 116, -35, ...]
The dataBytes and keyBytes are equal in both examples, meaning, when I inspect the bytes[], they have the same same values in the sequence.
When I compare the result hashes, they are both a bytes array of size 20, with different values. I've compared with other sources, and I believe the java implementation is the one that's correct. But, why are they different any way? I would have thought that since I'm comparing bytes with bytes, I shouldn't get a different result.
I have looked through many answers already that are posted in stackoverflow, and they all point to the encoding aspect (to use ascii encoding when transforming from string to bytes).
In advance, thanks for your time and let me know if I can provide any more info to make it more clear.
Upvotes: 0
Views: 22