'Java - Hashing with HmacSHA384 and encoding with HexDigest

I'm trying to replicate the same signature outcome as the Python code in Java.

Python Code Example:

secret = "1234abcd".encode()
encoded_payload = json.dumps(payload).encode()
b64 = base64.b64encode(encoded_payload)
signature = hmac.new(secret, b64, hashlib.sha384).hexdigest()

Current Java Code (I'm using Apache's Commons Codec for Hex encoding):

String secret = "1234abcd";
String b64 = Base64.getEncoder().encodeToString(payload.toString().getBytes());

Mac hasher = Mac.getInstance("HmacSHA384");
hasher.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA384"));
byte[] hash = hasher.doFinal(b64.getBytes(StandardCharsets.UTF_8));
String signature = Hex.encodeHexString(hash);

How should I go about doing this in Java?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source