jBCrypt checkpw returns false for correct password

1.2k Views Asked by At

I am hashing the password "password" using JBCrypt by doing

public User addUser(User newUser) {
        String passwordHash = BCrypt.hashpw(newUser.getPassword(), BCrypt.gensalt());
        newUser.setPassword(passwordHash);
        Object<User> user = new ObjectImpl<User>();
        return user.addObject(User.class, newUser);
    }

In the above, the newUser is delivered through a JAX-RS Restful web service.

In a ContextRequestFilter I'm trying to authenticate user as below:

public class AuthenticationFilter implements ContainerRequestFilter {

    private static final String AUTHORIZATION_HEADER = "Authorization";
    private static final String AUTHENTICATION_SCHEME = "Basic ";

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        List<String> authorizationHeader = requestContext.getHeaders().get(AUTHORIZATION_HEADER);
        if (authorizationHeader != null) {
            String authorizationToken = authorizationHeader.get(0);
            authorizationToken = authorizationToken.replaceFirst(AUTHENTICATION_SCHEME, "");
            String decodedString = Base64.decodeAsString(authorizationToken);
            StringTokenizer tokenizer = new StringTokenizer(decodedString, ":");
            try {
                String username = tokenizer.nextToken();
                String password = tokenizer.nextToken();
                Object<User> userObject = new ObjectImpl<User>();
                User user = userObject.getObjectByNamedQuery("User.byEmail", username);
                String hashedPassword = user.getPassword();
                if (BCrypt.checkpw(password, hashedPassword)) {
                    return;
                }
            } catch (NoSuchElementException e) {
                abortRequest(requestContext);
            } catch (NullPointerException e) {
                abortRequest(requestContext);
            }
        }
        abortRequest(requestContext);
    }

Here, when I send the password as "password", the abortRequest method still fires. I see that BCrypt.checkpw(password, hashedPassword) is returning false.

0

There are 0 best solutions below