I'm trying to hash a String in Java using ripemd160
to emulate the output of the following php:
$string = 'string';
$key = 'test';
hash_hmac('ripemd160', $string, $key);
// outputs: 37241f2513c60ae4d9b3b8d0d30517445f451fa5
Attempt 1
Initially I'd tried to emulate it using the following... however I don't believe it's possible to use ripemd160
as a getInstance` algorithm?
Or maybe it is and I just don't have it locally enabled?
public String signRequest(String uri, String secret) {
try {
byte[] keyBytes = secret.getBytes();
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac mac = Mac.getInstance("ripemd160");
mac.init(signingKey);
// Compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(uri.getBytes());
// Convert raw bytes to Hex
byte[] hexBytes = new Hex().encode(rawHmac);
// Covert array of Hex bytes to a String
return new String(hexBytes, "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Attempt 2
This led me to look for other ways to accomplish the above, through SO and Google I found that looking at BouncyCastle may be a better way to go.
I then found this post that talks about hashing using the same algorithm as I'd like and also BouncyCastle, it just doesn't use a key. (Cannot output correct hash in Java. What is wrong?)
public static String toRIPEMD160(String in) {
try {
byte[] addr = in.getBytes();
byte[] out = new byte[20];
RIPEMD160Digest digest = new RIPEMD160Digest();
byte[] rawSha256 = sha256(addr);
String encodedSha256 = getHexString(rawSha256);
byte[] strBytes = base64Sha256.getBytes("UTF-8");
digest.update(strBytes, 0, strBytes.length);
digest.doFinal(out, 0);
return getHexString(out);
} catch (UnsupportedEncodingException ex) {
return null;
}
}
I have this working as it would be expected to.
Issue
You'll note that in attempt 2 there is currently no way to supply a key for the hashing, my question is how can I adapt this function to be able to supply a key and accomplish the last stage of what I need to do to be able to emulate the original php function: hash_hmac('ripemd160', $string, $key);