Question

Ok, I'm a little confused. I'm trying to use MessageDigest to store my passwords in the database as MD5 hashes, and then pull the hash out to check a user's password when they try to log in.

So, when a user registers, at register.jsp, I use this code to convert their password (the string is called "password" in the code) to a hash (called "hashtext"):

MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
m.update(password.getBytes());
byte[] digest = m.digest();
BigInteger bigInt = new BigInteger(1,digest);
String hashtext = bigInt.toString(16);

while(hashtext.length() < 32 ){
  hashtext = "0"+hashtext;
}

Then, I need to manage how to check the password entered when a user tries to login. I have another page: login.jsp, where I run exactly the same code as above on the entered password, and check the result against the hash I pull from my database.

However, this doesn't work, and I assume it's because a new MessageDigest object is created (MessageDigest.getInstance("MD5");) and so the algorithm works differently.

Do I need to make sure the same MessageDigest object is used on login.jsp as register.jsp?

Was it helpful?

Solution

However, this doesn't work, and I assume it's because a new MessageDigest object is created (MessageDigest.getInstance("MD5");) and so the algorithm works differently.

This is not true.


Do I need to make sure the same MessageDigest object is used on login.jsp as register.jsp?

No.


Your problem is caused by something else. Probably you didn't save the hash of the initial password in the DB, or you didn't compare to the hash of the entered password, or you're comparing the hash on a system which uses a different default charset on getBytes(). Check the actual hash values before making conclusions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top