首页 > 解决方案 > 如果块没有正确执行

问题描述

我有一个 java web 项目,我有一个方法可以在用户登录时验证用户。我已经做了一个密码加密服务来验证,而不是他的密码是否合法。

    String email = request.getParameter("email");
    String password = request.getParameter("password");


    try {
        byte[] salt = LogicFacade.getSalt(email);

        byte[] attemptedPassword = LogicFacade.getEncryptedPassword(email);

        if (LogicFacade.authenticate(password, attempted password, salt))
//Here salt is null, whenever I try to log in, with a wrong username or password
 {
            User user = null;
            user = LogicFacade.login(email, password);
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            session.setAttribute("role", user.getRole());
            return user.getRole() + "page";
        } else {
            String errorMessage = "the username or password you have selected does not exist";
            throw new LoginSampleException(errorMessage);
        }

    } catch (NoSuchAlgorithmException | InvalidKeySpecException | LoginSampleException ex ) {
        String errorMessage = "We have an internal problem, but we are working as hard as possible, to solve it.";
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        throw new LoginSampleException(errorMessage);
    }
}

}

每当我输入错误的用户名或密码时,它都会说 Salt-parameter must be non-null。

这是因为我有一种方法可以从 SQL 数据库中检索用户的 salt,然后返回 null。

这是我的身份验证方法:

  public boolean authenticate(String attemptedPassword, byte[] encryptedPassword, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException, LoginSampleException {
        // Encrypt the clear-text password using the same salt that was used to
        // encrypt the original password
        byte[] encryptedAttemptedPassword = getEncryptedPassword(attemptedPassword, salt);

        // Authentication succeeds if encrypted password that the user entered
        // is equal to the stored hash
        return Arrays.equals(encryptedPassword, encryptedAttemptedPassword);
    }

我的问题是为什么在不满足 if 条件后它不执行 else 块。每当我调试项目时,在我尝试挖掘方法后它直接进入线程类?

有没有可能它可以进入 else 块而不立即抛出 NullPointerException?

标签: javamysqljspservlets

解决方案


将您的 if 条件更改为,

if (salt!=null && LogicFacade.authenticate(password, attempted password, salt)){
...if-block
} else {
...else-block
}

由于 salt null 表示您的数据库中不存在提供的电子邮件。


推荐阅读