【发布时间】:2018-06-09 18:56:03
【问题描述】:
我有一个 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?
【问题讨论】:
-
您需要彻底调试您的代码。我们不能为你做这件事。我能想象的唯一原因是
LogicFacade.authenticate(...)抛出异常。但它也可以是别的东西。 -
以上内容甚至无法编译 - 您的 if 语句缺少第二个)。发布代码时请更加小心!
-
这是一个错字,我很抱歉。是的,身份验证方法会引发 nullPointerException,但是我不知道为什么,因为一个值为 null,它不应该返回 false 吗?