Question

I'm creating a simple web application and want to store hashed passwords into a database. I need the hash function for the authentication token too (concatenating the user name and the date and send them with their hash to the client as the token).

I've found that MessageDigest Java class can help me with this. Here is one link. The basic idea goes like this:

public String digestString (String stringToHash) throws NoSuchAlgorithmException {
    MessageDigest sha256 = MessageDigest.getInstance("SHA-256");        
    byte[] stringBytes = stringToHash.getBytes();
    byte[] stringDigest = sha256.digest(stringBytes);
    return new String(stringDigest);
}

What I don't get is: In this code, how can I set the hash key? I need to be sure that the same key will be used in the verification process. How can I do that if I don't set the key?

BTW: I know I should add a salt (256 bytes in this case) to the hashed text before hashing it.

Was it helpful?

Solution

A hash uses no key. It's just a one-way algorithm. You give it something to digest, and it returns a hash. What it guarantees is that it's extremely hard to find the original input or any other input that leads to the same hash.

Your algorithm has two basic problems (besides the lack of salting):

  • it uses String.getBytes(), which relied on the default platform encoding, and thus differs from platform to platform. You should specify an encoding such as UTF-8.
  • it uses new String(byte[]), which has the same problem as above + an additional one: all the sequence of bytes are not valid character. To transform a purely binary byte array into a String, use a base64 encoding algorithm. apache commons codes has one.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top