开发者

How to use hash function in java for hashing the password?

I am trying to hash a password and save it in the database; I know hashing is a one way process. How can I check whether the user supplied password and the one stored in the database are same? I am using MD5 and I am getting different values fo开发者_运维百科r the same input when I perform hashing each time. Can anyone help?

String pass = "wor1ldcup";
    String pass1 = "wor1ldcup";

    DigestUtils du = new DigestUtils();
    byte[] b = du.md5(pass);
    byte[] b1 = du.md5(pass1);


The code you supplied is basically correct, with a couple of caveats:

  1. The methods of DigestUtils are all static, and hence should be invoked as:

    byte[] b = DigestUtils.md5(...);
    

    and not as

    DigestUtils du = new DigestUtils();  // wrong ... no need to instantiate
    byte[] b = du.md5(...);              // wrong ... never use an instance to
                                         //           call a static method.
    
  2. You don't show how you compare the b and b1, but b == b1 won't work, and neither will b.equals(b2) ... both compare references. You need to call Arrays.equals(b, b1).

  3. It is a bad idea to try to turn an MD5 hash into a String. Depending on the default character set, the conversion may turn out to be lossy; i.e. not reversible. If you want to store an MD5 hash in a database, it is better to encode as a String using (for example) base64 encoding, and save the encoded hash.


You really should use bcrypt instead of MD5 for password storage. Here is an article on why (there are many more).

The jBcrypt library works well.


Use:

import java.security.*;

byte[] password;
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(password, 0, password.length);
byte[] passwordHashed = messageDigest.digest();

Need to convert String to byte[] and byte[] to hex or Base64 String.


Here's a few things to check:

  • Are you comparing the hashes in the same case? i.e. are the alphabetic digits in the hashes in lowercase in both versions?
  • Is it possible that a leading 0 has been truncated from the front of one of the hashes?
  • Are you comparing two Strings using == ? Use .equals instead.

If all of those are ok, the hashing should return the same value each time for the exact same input.


At the most basic level, when using a hashing function for passwords you hash the password when initially storing it and then hash any attempts to match that original.

So, when you are trying to validate a password for an existing user your basic query would use the hashed version of the submitted password as a parameter.

SELECT * FROM Users where ID = 1234 and Password = @Password

binding @Password to du.md5(submittedPassword)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜