How can I create an SHA512 digest string in Java using bouncy castle?

女生的网名这么多〃 提交于 2019-11-29 23:18:51

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));

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.

Yes, you need to turn your byte array into a hex string. :-) Look into Apache Commons Codec, especially the Hex class.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!