2

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

Mike Curry
  • 1,609
  • 1
  • 9
  • 12
fihdi
  • 145
  • 1
  • 1
  • 12
  • possible duplicate of [Java arrays printing out weird numbers, and text](http://stackoverflow.com/questions/4479683/java-arrays-printing-out-weird-numbers-and-text) – JB Nizet Jun 06 '15 at 20:38
  • possible duplicate of [How do I print my Java object without getting "SomeType@2f92e0f4"?](http://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4) – DNA Jun 06 '15 at 20:47

4 Answers4

2

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.

Community
  • 1
  • 1
kervin
  • 11,672
  • 5
  • 42
  • 59
1

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));
Community
  • 1
  • 1
0

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())
Tobias
  • 7,723
  • 1
  • 27
  • 44
0

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());
Mimu Saha Tishan
  • 2,402
  • 1
  • 21
  • 40