I have hashed my passwords and stored them in a database. But I cannot login without decrypting the password. How do I do this?
My code that tries to do it but doesn't work:
@RequestMapping(method = RequestMethod.POST)
public String processLogin(Person user, BindingResult result,
@RequestParam("userName") String username,
@RequestParam("password") String password) {
try {
password = Hex.encodeHexString(MessageDigest.getInstance("SHA-256").digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
ValidateUser(username, password);
String destination = "";
if (success == true) {
destination = "redirect:/person.html";
}
else {
destination = "redirect:/index.html";
}
return destination;
}
public boolean ValidateUser(String username, String password) {
// Decrypt password here.
List<Person> users = service.getAllPersons();
for (Person allUsers : users) {
if (allUsers.getUserName().equals(username) &&
allUsers.getPassword().equals(password)) {
success = true;
}
}
return success;
}
And here is my md5 cryption:
public void setPassword(String password) {
String md5 = null;
try {
// Create MessageDigest object for MD5
MessageDigest digest = MessageDigest.getInstance("MD5");
// Update input string in message digest
digest.update(password.getBytes(), 0, password.length());
// Converts message digest value in base 16 (hex)
md5 = new BigInteger(1, digest.digest()).toString(16);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
this.password = md5;
}
You also encrypt the password that user inputs when logging in and then you compare two hashes. Therefore you need to use the same encryption method both for storing passwords and for checking them.
You don't decrypt a md5 hash, you encode the password provided by the user, and check it against the hash in the database.
For extra security you should also add a salt to the password before hashing. MD5 is not a good hashing algorithm for passwords, as it's designed for speed, that's the opposite of what you want, you want the password generation to be relatively slow, so use a more secure algorithm, and hash multiple times.
You can generate a hash using SHA-256:
Use the same algorithm when you insert the hash into the database, as when you receive the password during login, and match the hashes in the database.