2

I am trying to translate this line of code in Python:

signature = hmac.new("1234abcd", b64, hashlib.sha384).hexdigest()

I am trying to get the hash of a string with a secret key using SHA-384. However, I am trying to do this Java, does anyone know how to do it?

Also, I am asked for a nonce. What are the requirements for that?

1
  • HMAC-SHA-384 is not the same as SHA-384; see my comment below. Aug 29, 2017 at 0:22

1 Answer 1

4

You can use the MessageDigest with a method to convert bytes to Hex:

private static final String HMAC_SHA1_ALGORITHM = "HmacSHA384";

private static String bytesToHex(final byte[] hash) {
    final StringBuffer hexString = new StringBuffer();
    for (int i = 0; i < hash.length; i++) {
        final String hex = Integer.toHexString(0xff & hash[i]);
        if (hex.length() == 1) {
            hexString.append('0');
        }
        hexString.append(hex);
    }
    return hexString.toString();
}

public static void main(final String... args) throws NoSuchAlgorithmException, InvalidKeyException {
    final String nonce = "nonce";
    final String message = "test string";
    SecretKeySpec signingKey = new SecretKeySpec(nonce.getBytes(), HMAC_SHA1_ALGORITHM);
    final Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);
    System.out.println(bytesToHex(mac.doFinal(message.getBytes())));
}
3
  • 1
    Where do you use the key? hex(HMAC_SHA384(base64(payload), key=api_secret)) does not take a nonce. It takes a payload and a key.
    – Pablo
    Aug 28, 2017 at 23:01
  • 1
    HMAC-SHA-384 is not just SHA-384. See rfc 2104 and javax.crypto.Mac.getInstance("HmacSHA384") Aug 29, 2017 at 0:20
  • It's a bit confusing using nonce when you mean secret key, but otherwise great answer, cheers.
    – Will
    Oct 10, 2017 at 11:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.