6

I am now trying to encode the string using HMAC-SHA256 using Java. The encoded string required to match another set of encoded string generated by Python using hmac.new(mySecret, myPolicy, hashlib.sha256).hexdigest(). I have tried

    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
    sha256_HMAC.init(secretKey);

    byte[] hash = sha256_HMAC.doFinal(policy.getBytes());
    byte[] hexB = new Hex().encode(hash);
    String check = Hex.encodeHexString(hash);
    String sha256 = DigestUtils.sha256Hex(secret.getBytes());

after I print them out, hash, hexB, check and sha256 didn't provide the same result as the following Python encryption method

hmac.new(mySecret, myPolicy, hashlib.sha256).hexdigest()

So, I have try to looking for the library or something that work similar to the above Python function. Can anybody help me out?

Syon
  • 7,205
  • 5
  • 36
  • 40
Takumi
  • 355
  • 1
  • 7
  • 19

1 Answers1

11

Are you sure your key and input are identical and correctly encoded in both java and python?

HMAC-SHA256 works the same on both platforms.

Java

Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec("1234".getBytes(), "HmacSHA256");
sha256_HMAC.init(secretKey);
byte[] hash = sha256_HMAC.doFinal("test".getBytes());
String check = Hex.encodeHexString(hash);
System.out.println(new String(check));

Output
24c4f0295e1bea74f9a5cb5bc40525c8889d11c78c4255808be00defe666671f

Python

print hmac.new("1234", "test", hashlib.sha256).hexdigest();

Output
24c4f0295e1bea74f9a5cb5bc40525c8889d11c78c4255808be00defe666671f
Syon
  • 7,205
  • 5
  • 36
  • 40
  • Thank you so much, the problem solved. It was my stupid fault, incorrect secret Input. – Takumi Jul 31 '13 at 08:21
  • Thanks for the solution. I've compiled the Java and Python programs in a GitHub repo: https://github.com/AsadShakeel/HMAC-Java-Python-Hashing – Asad Shakeel May 31 '21 at 19:10