2

I am trying to hash my users password which is of string type using SHA-256

I am using SHA-256 to hash the string using the following method

String text = "abc";
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes("UTF-8"));

To convert the btye array to string , I used the following method

String doc2 = new String(hash, "UTF-8");

When i print doc2 to output , i get rubbish

�x����AA@�]�"#�a��z���a�

What am i doing wrong ??? How do i hash a string using SHA-256 and convert it back to string ??

Community
  • 1
  • 1
Computernerd
  • 7,378
  • 18
  • 66
  • 95
  • Hashing is a one way function. If your intention is to try and get back the password from the hash, it is impossible. – anonymous Apr 02 '14 at 04:47

2 Answers2

8

this will pring hex representation of hash

String s = DatatypeConverter.printHexBinary(hash)

you cannot get original string from hash

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

SHA256 returns pure binary output, with all values from 00 to FF essentially equally likely for each character.

For text output, you'll need to convert it to a text form, like Base64 encoding

byte[] encodedBytes = Base64.encodeBase64("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));

The only way to go from a cryptographically sound hash (or most hashes, even cryptographically unsound ones) back to the original input is to apply the hash to input after input until you get the same result - that's either the original input, or a collision.

Anti-weakpasswords
  • 2,604
  • 20
  • 25