Search code examples
javahmacsha

How to generate HMAC SHA 256 using hmacutils in java


I've been trying to generate an HMAC for an API using code like so:

public static void main(String[] args) {

    byte[] hmacSha256 = HmacUtils.hmacSha256(API_SECRET, "totalParams");

    System.out.println((Base64.getEncoder().encodeToString(hmacSha256)));
}

But when I use the string I get in my API call I receive the error:

{"code":-1100,"msg":"Illegal characters found in parameter 'signature'; legal range is '^[A-Fa-f0-9]{64}$'."}

I thought that it meant I had to convert to hex, but the hex is not working either.

I don't care about the implementation, I just want a valid signature. Anyone know how to generate a valid signature in any way?


Solution

  • See this answer to a similar question, and then this answer to convert your byte[] to hex instead of using Base64.

    (Short version: You've got 256 bits of hash, and the API is expecting 64 characters. Base64 gives you 44(ish), but hex should give you 64)