Converting String to Sha-256 Hash

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 06:29:17

问题


I want to convert a String to a SHA-256 Hash. I am using this code:

String text = "YOLO";
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes("UTF-8"));
System.out.println(hash.toString());

The problem is, when I start the program, it prints

[B@28d93b30

Why is this, and how can solve this?

Thanks in advance,

Fihdi


回答1:


As others have mentioned, you're using the default toString() method which simply outputs the class name and hashcode

If you want a hex print out of the contents of the byte array try... Hex.encodeHexString(byte[] data) from Apache Commons.

Also How to convert a byte array to a hex string in Java? has some examples for doing this without a library.




回答2:


To print the bytes as hex (instead of that result, explained in How do I print my Java object without getting "SomeType@2f92e0f4"?), simply run:

System.out.println((new HexBinaryAdapter()).marshal(hash));



回答3:


In JAVA, arrays do not override Object.toString(). Therefore, hash.toString() does not return a representation of the contents of the array, but rather a representation of the array itself. Apparently, this representation of an array is not very useful. The default toString() implementation returns

 getClass().getName() + '@' + Integer.toHexString(hashCode())


来源:https://stackoverflow.com/questions/30687160/converting-string-to-sha-256-hash

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