Understanding Password Hashing in Java with MessageDigest

I am creating a simple web application and want to store hashed passwords in a database. I need a hash function for an authentication token (concatenating the username and date and sending them with a hash to the client as a token).

I found that the MessageDigest Java class can help me with this. Here is one link . The basic idea is 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); } 

I do not get: In this code, how can I set the hash key? I must be sure that the same key will be used in the verification process. How can I do this if I do not install the key?

By the way: I know that I have to add salt (256 bytes in this case) to the hashed text before hashing it.

+4
source share
1 answer

The hash does not use a key. This is just a one-way algorithm. You give it something to digest, and it returns a hash. This ensures that it is very difficult to find the original input or any other input that leads to the same hash.

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

  • it uses String.getBytes (), which relied on the default platform encoding and therefore differs from platform to platform. You must specify an encoding such as UTF-8.
  • it uses the new String (byte []), which has the same problem as above + additional: the entire sequence of bytes is invalid. To convert a pure binary byte array to String, use the base64 encoding algorithm. The apache sharing codes have one.
+7
source

Source: https://habr.com/ru/post/1389337/


All Articles