I am trying to create a signature using the HMAC-SHA256 algorithm and this is my code. I am using US ASCII encoding.
final Charset asciiCs = Charset.forName("US-ASCII");
final Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
final SecretKeySpec secret_key = new javax.crypto.spec.SecretKeySpec(asciiCs.encode("key").array(), "HmacSHA256");
final byte[] mac_data = sha256_HMAC.doFinal(asciiCs.encode("The quick brown fox jumps over the lazy dog").array());
String result = "";
for (final byte element : mac_data)
{
result += Integer.toString((element & 0xff) + 0x100, 16).substring(1);
}
System.out.println("Result:[" + result + "]");
The result that I am getting from the above code is:
f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8
This is same as to that of shown in the wiki
HMAC_SHA256("key", "The quick brown fox jumps over the lazy dog") = 0x f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8
except for the 0x
.
I am looking for ideas/comments if I am doing everything right or may be I can improve my code.
Java simple code to generate encoded(HMAC-x) signatures. (Tried using Java-8 and Eclipse)
Try this
Sorry for being late, I have tried all above answers but none of them is giving me correct value, After doing the lot of R&D I have found a simple way that gives me exact value.
Declare this method in your class
}
Use this like
Verification
1.Android studio output 2. Online HMAC generator Output(Visit here for Online Genrator)
The 0x just denotes that the characters after it represent a hex string.
So the 0x is just to clarify what format the output is in, no need to worry about it.
Here is my solution:
Or you can return the hash encoded in Base64:
The output in hex is as expected:
This is working fine for me
I have add dependency
ref: http://mvnrepository.com/artifact/commons-codec/commons-codec/1.9
my function
If but any chance you found a solution how to calculate HMAC-SHA256 here, but you're getting an exception like this one:
Then use: