29

I am working on web application project in Spring Hibernate MVC. I am storing encoded passwords in a database using Bcrypt algorithm in Spring security.

Now I want to get that encoded password to be decoded to deactivate a use account where in I am giving user email and password to verify before user deactivate the account. I have a problem in getting the decoded password.

Can anyone help me to get out of it or any alternate solution for my requirement?

informatik01
  • 16,038
  • 10
  • 74
  • 104
arch
  • 1,363
  • 2
  • 14
  • 30

2 Answers2

49

The problem is solved by using below code:

BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();  
encoder.matches(password, user.getPassword());  

password - from form(JSP)
user.getPassword() - from database

BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
if(email.equalsIgnoreCase(user.getEmail()) && encoder.matches(password, user.getPassword())) {
    userService.deactivateUserByID(user.getId());
    redirectAttributes.addFlashAttribute("successmsg", "Your account has been deactivated successfully.");
    model.setViewName("redirect:/logout");
}else{
    redirectAttributes.addFlashAttribute("errormsg", "Email or Password is incorrect");
    model.setViewName("redirect:/app/profile/deactivate");
}
A. Sarid
  • 3,916
  • 2
  • 31
  • 56
arch
  • 1,363
  • 2
  • 14
  • 30
  • 17
    Just to be clear - this doesn't actually decode the encoded password as implied by the question. Per the Spring docs, `BCryptPasswordEncoder.matches()` verifies the encoded password obtained from storage matches the submitted raw password after it too is encoded. – Shaggy Sep 02 '16 at 12:42
8
BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder();  
boolean isPasswordMatches = bcrypt.matches(userenteredpasswordWithotEncryoted, encryptedPasswordFromDb);

Example:

boolean isPasswordMatches = bcrypt.matches(
        "Truck123",
        "$2a$10$kcVH3Uy86nJgQtYqAFffZORT9wbNMuNtqytcUZQRX51dx6IfSFEd."
);


if (isPasswordMatches) { // correct password
    ...
} else { // Wrong Password
    ...
}
informatik01
  • 16,038
  • 10
  • 74
  • 104
user12249582
  • 81
  • 1
  • 2