首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >If块未正确执行

If块未正确执行
EN

Stack Overflow用户
提问于 2018-06-10 02:56:03
回答 2查看 95关注 0票数 0

我有一个java web项目,其中有一个方法可以在用户登录时对其进行验证。我做了一个密码加密服务,以验证他的密码是否合法。

代码语言:javascript
复制
    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必须为非空。

这是因为我有一个方法可以从用户、从SQL数据库检索盐,然后返回null。

下面是我的身份验证方法:

代码语言:javascript
复制
  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?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-10 03:23:32

将if条件更改为,

代码语言:javascript
复制
if (salt!=null && LogicFacade.authenticate(password, attempted password, salt)){
...if-block
} else {
...else-block
}

因为salt null意味着您的数据库中不存在所提供的电子邮件。

票数 1
EN

Stack Overflow用户

发布于 2018-06-10 03:05:37

这是因为if块在try块内,当抛出异常时,控制转移到catch块,然后程序退出

要纠正这个错误,您只需检查

代码语言:javascript
复制
if(salt==null)

希望它能帮上忙!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50777535

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档