Updating BCrypt Hash Password of User via JPA
I am stucked into a very weird problem. I have not used BCrypt before for
password security. The functionality of the app is to Register a user and
then come with Change Password option. When I register a user and Login in
the app it works fine. But when I update the password I would no more be
able to Login with the new password.Because this function always return
false after updating the password:
BCrypt.checkpw(password.trim(), user.getPasswordHash())
Below the code is given for the save and update function.
*NOTE: I am using Java, GWT, Errai and JPA *
Create User
public void createUser(User user) {
String passwd = user.getPassword();
String salt = BCrypt.gensalt();
user.setPassword(""); // remove the password
user.setPasswordHash(BCrypt.hashpw(passwd, salt));
commonDAO.save(user);
}
Update User (Change Password)
public void updateUser(String pwd) {
String salt = BCrypt.gensalt();
User user2=sessionContext.getCurrentUser();
user2.setPasswordHash(BCrypt.hashpw(pwd, salt));
commonDAO.merge(user2);
}
Following is the login function :
public User login(String username, String password, Boolean rememberMe) {
try {
User user = userDAO.fetchUserByName(username);
System.out.println(user.getId()+":"+user.getUsername());
if (!BCrypt.checkpw(password.trim(), user.getPasswordHash())) {
throw new AuthenticationException("Failure in authentication");
}
return user;
} catch (org.apache.shiro.authc.AuthenticationException e) {
throw new AuthenticationException("Failure in authentication");
// log.error("Failure in authentication", e);
}
}
No comments:
Post a Comment