News for hackers. Stuff that matters.
Re:HMAC signatures in Java by bazzargh on Monday July 23, 2012 @07:38AM (#4280462)
It would help to test your code before posting it. You haven't imported javax.crypto.Mac, so it won't compile.

Also, your conversion from strings to bytes and back is just wrong - this will not work as expected when run on machines with a different platform encoding. This is a real problem when writing security code - I've seen code that attempted to get the bytes from passwords on a japanese website in ISO-8859-1, effectively making all passwords of the same length the same value.

  // get bytes in UTF-8 - always supported in java
  // as its specified in the JLS, and supports every
  // code point that can appear in the string
  byte[] secretByte = macKey.getBytes("UTF-8");
  byte[] dataBytes = macData.getBytes("UTF-8");
  SecretKey secret = new SecretKeySpec(secretByte, "HMACSHA256");
  mac.init(secret);
  byte[] doFinal = mac.doFinal(dataBytes);
  // Hex supplies a method to get a string directly. Use it.
  String checksum = Hex.encodeHex(doFinal);
Re:HMAC signatures in Java by java-only on Monday July 23, 2012 @08:52AM (#4280659)
yes you are right.I've corrected both.Thank you :)
Re:HMAC signatures in Java by bazzargh on Monday July 23, 2012 @12:06PM (#4281636)
You're still doing it wrong. Look at the last line of my code snippet.

The code you've used will encode to hex bytes in UTF-8, but then you turn that into a string with the platform default character set, which may not be compatible (eg: any double-byte encoding). Use the method that Hex provides. If you really need to you can do new String(bytes, hex.getCharEncoding()), but it's needless complexity.