Christina
Christina

Reputation: 411

openssl dgst -sha256 -hmac and JAVA solution differ

I want to replicate:

echo -n "a" | openssl dgst -binary -sha256 -hmac "a"

in Groovy (Java). So far I've done this:

def sha = Mac.getInstance("HmacSHA256")
SecretKeySpec secret_key = new SecretKeySpec("a".getBytes(), "HmacSHA256")
sha.init(secret_key)
def shaCrypted = new String(sha.doFinal('a'.getBytes()))
println(shaCrypted)

but unfortunately I don't get the same results.

Can anyone tell me what I am missing? Thanks in advance!

Upvotes: 2

Views: 695

Answers (1)

ravenskater
ravenskater

Reputation: 794

Transform it into hexadecimal:

byte[] signature = sha.doFinal('a'.getBytes())
StringBuilder sb = new StringBuilder(signature.length * 2);
for(byte b: signature) {
   sb.append(String.format("%02x", b));
}
sb.toString();

Upvotes: 0

Related Questions