0

I have some String I'd like to hash using the SHA-256 way. I looked a bit on the internet and to my great surprise, I can't find a simple way to do so. I'm aware of the MessageDigest class wich seems to provide everything I need except one thing : a method like this : String hash256(String txt) I also know there are ways to do so (for instance : here) but I'm reluctant to writing more than one line for something probably already existing. Do you guys know if such a thing exists ?

EDIT : it looks like I wasn't clear enough. Is there an existing method equivalent to the following code in JDK ?

public String hash256(String txt){
    MessageDigest sha = MessageDigest.getInstance("SHA-256");
    sha.update(txt.getBytes());
    byte[] digest = sha.digest();
    return bytesToString(digest);
}
merours
  • 4,076
  • 7
  • 37
  • 69
  • 1
    Btw, that dup wasn't hard to find: google "java SHA256" and it's the top hit. No sure what you meant by "I searched the web" :/ – Bohemian Aug 20 '13 at 16:14
  • @Bohemian As i said, I want to know if there is a jdk method wich can hash a String to a String. The examples you provide give me bytes (I know how to treat them, but I'd rather not recode something already existent). – merours Aug 21 '13 at 07:06

2 Answers2

3
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(stringAsbytes);
stringAsBytes = md.digest();

Then convert the bytes to a string. Make sure you specify the string encoding.

Dodd10x
  • 3,344
  • 1
  • 18
  • 27
  • The point of my question is : is there an existing method doing that all (and not just hashing to bytes) ? – merours Aug 21 '13 at 07:07
  • 2
    The point of my answer was to show you how simple it was to do what you wanted with the existing API. There isn't a single line solution to every problem. – Dodd10x Aug 21 '13 at 16:04
3

You can use DigestUtils.sha256() from Apache Commons Library.

Marcelo
  • 11,218
  • 1
  • 37
  • 51