2

I am trying an example:

String hashAlgorithm ="sha-256"
...
md=MessageDigest.getInstance(hashAlgorithm);
byte[] enteredPasswordDigest = md.digest(policy.getPassword().getBytes());
if (!MessageDigest.isEqual(enteredPasswordDigest, realPassword.getBytes())) {
    ...
}

However, the hashed password is stored as a string in the database. When I do that comparison, it fails. When I debug it, enteredPasswordDigest has 32 byte length and realPassword.getBytes() has 64 byte length.

What did I miss?

1
  • Are you sure the the length of realPassword.getBytes() is 64 bit (=8 byte) not byte? Because I don't know a secure hash function that would create an 64 bit output. Commented Jun 8, 2012 at 9:59

3 Answers 3

1

Simply,

  • take the entered password and hash/digest it
  • convert the byte[] to string
  • compare that string to the already-hashed-password string in the DB

Try this,

String hashedStr = new String(enteredPasswordDigest);
if (!hashedStr.equals(realPassword)) {
  ...
} else {
  ...
}

Docs: String.getBytes()

The behavior of this method when this string cannot be encoded in the default charset is unspecified. The java.nio.charset.CharsetEncoder class should be used when more control over the encoding process is required.

Sign up to request clarification or add additional context in comments.

2 Comments

hashedStr's length is 32 but realPassword is 64?
@kamaci: realPassword.getBytes().length is 64, I'm not using that. Just use the string realPassworditself, as shown in my post. And the length of that is indeed 32.
0

Assuming realPassword is a String, the problem might be that Java strings are UTF16, ie 2 bytes per character. Try printing both byte arrays to get a better insight in whats going on.

Comments

0

I solved my question with that point: Hashed password as a string at database is "hex". That is the main point. So I got the hex of entered password's byte array digest. Then I compared strings that has hex values.

1 Comment

Now that you've managed what you were looking for, you may want to consider looking at salting it for better security.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.