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
  • 35,162
  • 12
  • 84
  • 155
HomeIsWhereThePcIs
  • 1,067
  • 1
  • 14
  • 30
  • 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

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
  • 35,162
  • 12
  • 84
  • 155
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,628
  • 3
  • 32
  • 37