Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenSSL Hmac and BouncyCastle Hmac Differ

I am trying to figure out why an hmac in openssl is not giving me the same result as an hmac in java.

in open ssl

echo -n "Hello" | openssl dgst -sha256 -hmac 04d6b077d60e323711b37813b3a68a71

Output: cc598d8840fe409d5fcc1c1c856f9e8c311d1c458850615555857b023f1cd94c

In java

String key = "04d6b077d60e323711b37813b3a68a71"
SecretKeySpec key2 = new SecretKeySpec(Hex.decode(key), "RAW");
String data = "Hello";
Mac hmac = Mac.getInstance("Hmac-SHA256", BouncyCastleProvider.PROVIDER_NAME);
hmac.init(key2)
byte[] bytes = hmac.doFinal(data.getBytes());
System.out.println(Hex.toHexString(bytes));

Output: 877f9c8eb44c20987e3978928fbfcea0f1cf99c88f9db904596921b7ecf0613b

I am at a loss why these are different.

like image 993
MJ Harkins Avatar asked Oct 01 '22 10:10

MJ Harkins


1 Answers

OpenSSL treats -hmac key option as if the key is just an array of bytes represented as corresponding ASCII characters. The key is thus limited to contain only printable characters.

You can get the same results in Java as in OpenSSL by using

SecretKeySpec key2 = new SecretKeySpec( key.getBytes("ASCII"), "RAW" );

Alternatively you can use openssl dgst -sha256 -mac HMAC -macopt hexkey:string where string will be treated as a HEX encoded key.

like image 71
Oleg Estekhin Avatar answered Oct 12 '22 10:10

Oleg Estekhin