Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Java and PHP SHA256 HMAC Compatibility

843811Feb 23 2009 — edited Feb 23 2009
Hi,

I am trying to create a SHA256 HMAC in PHP which I would then like to pass to a Java Servlet as an HTTP request parameter. The issue I am running into is that the hash I am getting in Java is different than what is being produced from my PHP code. I have spent hours on this issue and cant figure out whats wrong... Does anyone see any issues with the following two example code blocks? Thanks!!

Java Code (Hex class is from the Apache Commons Codec project):
String algorithm = "HmacSHA256";

//hex encoded 256 bit key
String encryptionKey = "8017aa25b6c6ba0c56110e3544718361af905f83f151f4f3af8f029cd36ee84d";
String message = "the quick brown fox jumped over the ...";

byte[] keyBytes = Hex.decodeHex(encryptionKey.toCharArray());
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, algorithm);

Mac mac = Mac.getInstance(algorithm);
mac.init(secretKeySpec);
byte[] macBytes = mac.doFinal(message.getBytes());

String hexBytes = new String(Hex.encodeHex(macBytes));
System.out.println(hexBytes);        

//Produces Hash: ff6733f1880d248f7d9ba0723219727cb2535588945b62a6fc9829afc1fe22b5
PHP Code:
//hex encoded 256 bit key
$encryptionKey = "8017aa25b6c6ba0c56110e3544718361af905f83f151f4f3af8f029cd36ee84d";
$message = "the quick brown fox jumped over the ...";

$encryptionKeyBytes = pack('H*', $encryptionKey);
$rawHmac = hash_hmac('sha256', $encryptionKeyBytes, $message, true);
echo bin2hex($rawHmac)."\n";

//Produces Hash: b6070cb581bf06ad3cdbe8968773d76e9d2cadc5c138f8f978f1eb442846e21e

Comments

Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Mar 23 2009
Added on Feb 23 2009
3 comments
3,431 views