简体   繁体   中英

Converting String to Sha-256 Hash

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

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.

要将字节打印为十六进制(而不是该结果,在How do I print my Java object without getting "SomeType@2f92e0f4"? 中进行了解释),只需运行:

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

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 d efault toString() implementation returns

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

I have also faced this type of issue and then solve in this way.

String text = "YOLO";
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
String encoded = DatatypeConverter.printHexBinary(hash);        
System.out.println(encoded.toLowerCase());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM