I have a big code in Java that hashes a string using SHA-512, and I've been unable to get similar results in Bash. So I decided to simplify it the most I was able to hunt for the problem, and came up with this small piece of code:
import java.math.BigInteger;
import java.security.MessageDigest;
class Test {
public static void main(String []args) throws Exception {
String SECRET = "secret";
String STRING = "string";
MessageDigest digest = MessageDigest.getInstance("SHA-512");
digest.update(SECRET.getBytes("UTF-8"));
byte[] d = digest.digest(STRING.getBytes("UTF-8"));
System.out.println(new BigInteger(1, d).toString(16));
}
}
which returns:
26620758babadb008ee7b98e1bb07351f08d49228c15f6f31c4ee75cb9a26f5079b81c01f14f78cf5f9639e49d7319ee3c3fcc1f94e686b8d605c93f2ab9fb4
From my understanding, this would be equivalent to:
#!/bin/bash
SECRET="secret"
STRING="string"
echo -n "$STRING" | openssl sha512 -hmac "$SECRET"
but this returns:
c13223b6f7331a608ec24bf3adfd8f599622b4d5b28cd27f9dcf92430a6263f435d07ff59809785ef04c5cb4aefd02357578efc8862e254a7505e26c76806194
The only thing I have noticed is that if I change the value of toString(16)
, the result changes too. But from reading its documentation, I could not figure out what it does!
Try
I get
026620758babadb008ee7b98e1bb07351f08d49228c15f6f31c4ee75cb9a26f5079b81c01f14f78cf5f9639e49d7319ee3c3fcc1f94e686b8d605c93f2ab9fb4 -
(there is a leading zero). The issue with your command is the argument
-hmac
. It works here withOutput of
(stdin)= 026620758babadb008ee7b98e1bb07351f08d49228c15f6f31c4ee75cb9a26f5079b81c01f14f78cf5f9639e49d7319ee3c3fcc1f94e686b8d605c93f2ab9fb4
Finally, changing the value you pass to
toString()
changes the number's radix (or base).