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 for 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:
The methods of
DigestUtilsare allstatic, and hence should be invoked as:and not as
You don’t show how you compare the
bandb1, butb == b1won’t work, and neither willb.equals(b2)… both compare references. You need to callArrays.equals(b, b1).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.