HMAC-SHA1: How to do it in Java?

I pass some values โ€‹โ€‹using HMAC-SHA1 using the following code in Java:

public static String hmacSha1(String value, String key) { try { // Get an hmac_sha1 key from the raw key bytes byte[] keyBytes = key.getBytes(); SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1"); // Get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); // Compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(value.getBytes()); // Convert raw bytes to Hex byte[] hexBytes = new Hex().encode(rawHmac); // Covert array of Hex bytes to a String return new String(hexBytes, "UTF-8"); } catch (Exception e) { throw new RuntimeException(e); } } 

Hex() owned by org.apache.commons.codec

PHP has a similar hash_hmac(algorithm, data, key) function that I use to compare the values โ€‹โ€‹returned by my Java implementation.

So, the first attempt:

 hash_hmac("sha1", "helloworld", "mykey") // PHP 

which returns: 74ae5a4a3d9996d5918defc2c3d475471bbf59ac

My Java function returns 74ae5a4a3d9996d5918defc2c3d475471bbf59ac .

Good, it seems to work. Then I try to use a more complex key:

 hash_hmac("sha1", "helloworld", "PRIE7$oG2uS-Yf17kEnUEpi5hvW/#AFo") // PHP 

which returns: e98bcc5c5be6f11dc582ae55f520d1ec4ae29f7a

So far this time my Java impl returns: c19fccf57c613f1868dd22d586f9571cf6412cd0

The hash returned by my PHP code is not equal to the value returned by my Java function, and I cannot understand why.

Any tips?

+47
java hash hmac sha1
Jun 10 2018-11-22T00:
source share
4 answers

On your PHP side, use single quotes around the key, so the $ character is not considered a reference to a variable. i.e.,

 hash_hmac("sha1", "helloworld", 'PRIE7$oG2uS-Yf17kEnUEpi5hvW/#AFo') 

Otherwise, the key you really get is PRIE7-Yf17kEnUEpi5hvW/#AFo (assuming the variable $oG2uS is undefined).

+51
Jun 10 2018-11-21T00:
source share

Recommend Apache Common Codec Library , simple and easy to use. HmacUtils.hmacSha1Hex(key, string_to_sign);

+11
Jan 13 '16 at 6:21
source share

Any double-quoted $ character ("") is treated as a variable in PHP. You can avoid the error by using single quotes as indicated by the previous commenter, or you can avoid the dollar sign as shown below.

 hash_hmac("sha1", "helloworld", "PRIE7\$oG2uS-Yf17kEnUEpi5hvW/#AFo") 

$ Notification now \ $

+7
Apr 27 '13 at 16:17
source share

In Java and using maven :

Add the following dependency to pom.xml :

  <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec --> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.4</version> </dependency> 

and then try to sign it using this

 HmacUtils.hmacSha1Hex(key, string_to_sign); 
0
Oct. 30 '17 at 15:38
source share



All Articles