0

I've written this simple Java snippet to SHA-256 a string:

public static void main(String[] args) throws NoSuchAlgorithmException {
    MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
    String input = "00010966776006953D5567439E5E39F86A0D273BEE";
    byte[] output = sha256.digest(input.getBytes());
    System.out.println(new String(output));
}

Running SHA-256 using this tool gives the output 3CC2243D50E87857A233965AA6B68B37563BFCC52B3C499FBB259B9AA87FFF40, but when I run it myself I get <�$=P�xW�3�Z���7V;��+<I��%����@. It looks like something is going wrong with the byte conversion, but I'm not exactly sure what.

David says Reinstate Monica
  • 19,209
  • 22
  • 79
  • 122
  • 1
    See: [How to convert a byte array to a hex string in Java?](https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java). – teppic Apr 04 '18 at 02:03
  • See this: [https://stackoverflow.com/questions/23756832/cant-get-to-have-sha-256-hash-working-with-my-spring-security](https://stackoverflow.com/questions/23756832/cant-get-to-have-sha-256-hash-working-with-my-spring-security) – qxzsilver Apr 04 '18 at 02:05

2 Answers2

1

You are correct that something was wrong when you tried to convert byte[] to string. Here is a code that works :)

public static void main(String[] args) throws NoSuchAlgorithmException {
    final String input = "Nishit";
    final MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(input.getBytes());
    final byte[] data = md.digest();
    StringBuilder sb = new StringBuilder(data.length * 2);
    for (byte b : data) {
        sb.append(String.format("%02x", b));
    }
    System.out.println(sb.toString());

}
Nishit
  • 1,276
  • 2
  • 11
  • 25
0

What it is really happenning is that the SHA256 returns a 256-bit hash value. So what you're printing is those bytes as if they were characters and their respective character values is all that gibberish.

What the online tool is returning you is the representation of that value in hexadecimal format.

Notice that you're getting, (with the tool) 64 bytes IE 64 characters when 256-bit is equal to 32 bytes (32 charaters you may think). That is because to represent a whole byte in hexadecimal format 2 characters are needed. 4 most significative bits take one character and the other less significative bits take another one.

Some random IT boy
  • 7,569
  • 2
  • 21
  • 47