0

I am trying to hash a string using SHA-256 but the result is wrong and contains special characters.

Code:

String password = "test";
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] sha256Result = md.digest(password.getBytes(StandardCharsets.UTF_8));
String result = new String(sha256Result, StandardCharsets.UTF_8);

Result string:

��Ё�L}e�/��Z���O+�,�]l��
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
HomeIsWhereThePcIs
  • 1,273
  • 1
  • 19
  • 37
  • The returned array is the raw bytes of the hash, if you want it in hex you should check [this question](https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java). – Haem Sep 29 '17 at 12:06
  • Please replace `hasing` by `hashing` in your headline to make it easier to find your article – Christoph S. Oct 11 '22 at 09:08

2 Answers2

1

The hashing procceed correctly, but the result is consisted of array of bytes. To make it readable, use the StringBuffer. As example of conversion, take a look on the example on Mkyong's webpage.

StringBuffer sb = new StringBuffer();
    for (int i = 0; i < sha256Result.length; i++) {
    sb.append(Integer.toString((sha256Result[i] & 0xff) + 0x100, 16).substring(1));
}
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
1

I think the way you hash it is ok. If you want it as a hex string after:

import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
String hex = (new HexBinaryAdapter()).marshal(md.digest(password.getBytes(StandardCharsets.UTF_8)));
Liviu Stirb
  • 5,876
  • 3
  • 35
  • 40