This unit test is failing:
public void testDigest() throws NoSuchAlgorithmException {
String hashExpected = \"150a14ed5bea6cc731cf86c41566ac427a8db48
Just an addition to Kevin's answer: Since Java 5, you can use String.format("%0128x", new BigInteger(1, digesta))
instead of commons-codec to format the byte array as a 128 digit hex encoded number with leading zeros.
Since BouncyCastle 1.49 there is a handful toHexString
method in the Hex
class. For example:
Hex.toHexString(digest);
will return you the hash digest as a Java String
in a hexadecimal format.
For reference see BouncyCastle javadoc or grepcode.
Yes, you need to turn your byte array into a hex string. :-) Look into Apache Commons Codec, especially the Hex class.
The value you're expecting is a Hex-encoded value. You're creating a String based on the raw bytes, which won't work.
You should use the standard Java Crypto API whenever possible instead of BouncyCastle specific APIs.
Try the following (the Hex library comes from commons-codec):
Security.addProvider(new BouncyCastleProvider());
String data = "hello world";
MessageDigest mda = MessageDigest.getInstance("SHA-512", "BC");
byte [] digesta = mda.digest(data.getBytes());
MessageDigest mdb = MessageDigest.getInstance("SHA-512", "BC");
byte [] digestb = mdb.digest(data.getBytes());
System.out.println(MessageDigest.isEqual(digesta, digestb));
System.out.println(Hex.encodeHex(digesta));