3

What is the Java equivalent of http://php.net/manual/en/function.hash-hmac.php ?

I need to specify both the data and the secret key to generate a SHA512 hash.

Best I've found so far is http://commons.apache.org/codec/apidocs/org/apache/commons/codec/digest/DigestUtils.html#sha512Hex(java.lang.String) but how do I specify the key?

siamii
  • 23,374
  • 28
  • 93
  • 143

2 Answers2

2

Bouncy Castle includes an HMAC class which can use any digest (=hash) available, including SHA-256.

rossum
  • 15,344
  • 1
  • 24
  • 38
0

I recommend using Apache Commons Codec and especially its DigestUtils.

For instance like this:

public String calcSha(String secret, String data) {
    return DigestUtils.sha512Hex(secret + data);
}
M.L.
  • 4,686
  • 1
  • 19
  • 15
  • I updated the answer. The PHP-version is probably doing similar thing inside. – M.L. Oct 10 '11 at 14:34
  • 1
    I don't get it- you pass the secret with the data as a concatenated string? Why aren't they two separate parameters? – IcedDante May 26 '16 at 19:30
  • This is incorrect, HMAC (per the original question) would be `H(secret XOR outer-padding, H(secret XOR inner-padding, data))` ([RFC 2104](https://tools.ietf.org/html/rfc2104)), not just a naive concatenation of a secret and a message. This is to [resist length extension attacks](https://en.wikipedia.org/wiki/Length_extension_attack). Also, do not use `String` types everywhere at such a low level, prefer to encode/decode for armoring at the boundaries, and only if necessary. @IcedDante: That's because this isn't a HMAC, a normal hash function has only one parameter and no notion of secret keys. – tne Jul 21 '19 at 10:07