Interop: HmacSHA1 in Java and dotNet
In the application, we calculate SHA1Hmac in java using the following:
SecretKey key = new SecretKeySpec(secret, "HmacSHA1");
Mac m = Mac.getInstance("HmacSHA1");
m.init(key);
byte[] hmac = m.doFinal(data);
And later, hmac is checked in C # - on a smart card - using:
HMACSHA1 hmacSha = new HMACSHA1(secret);
hmacSha.Initialize();
byte[] hmac = hmacSha.ComputeHash(data);
However, the result is not the same. Am I missing something important?
The inputs appear to be the same. Here are some examples of input:
Data: 546573746461746131323341fa3c35
Key: 6d795472616e73616374696f6e536563726574
Result Java: 37dbde318b5e88acbd846775e38b08fe4d15dac6
Result C#: dd626b0be6ae78b09352a0e39f4d0e30bb3f8eb9
I wouldn't mind implementing my own hmacsha1 on both platforms, but using what already exists ....
Thanks!
a source to share
With this Java code:
static byte[] doHMAC(byte[] data, byte[] secret)
{
SecretKey key = new SecretKeySpec(secret, "HmacSHA1");
Mac m = Mac.getInstance("HmacSHA1");
m.init(key);
return m.doFinal(data);
}
then I get dd626b0be6ae78b09352a0e39f4d0e30bb3f8eb9
what you have from your C # implementation. Also, I have confirmed this value regarding my own implementation of HMAC and SHA-1 (in Java), and I got this result as well.
It seems like your Java code is wrong, but not in the part you show (other than yours m.init(secret)
, which doesn't compile - it should be m.init(key)
). As my code shows, the Java HMAC / SHA-1 implementation is correct and you are calling it correctly. I am assuming you are not entering the correct data or key.
(I am using Sun JDK 1.6.0_16)
a source to share