[java] check password against DB

To check the password against the database encoded value is simple, but it is not supported out of the box. You’ll have to convert the generated hash into hex format
[code language=”java”]
byte[] encoded = md.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < encoded.length; i++) {
sb.append(Integer.toString((encoded[i] & 0xff) + 0x100, 16).substring(1));
}
[/code]
Here’s a complete example:
[code language=”java”]
public boolean validate(String username, String password) {
final Query query = em.createQuery("SELECT u FROM User u WHERE u.username = :username");
query.setParameter("username", username);

List<User> foundUsers = (List<User>) query.getResultList();
if (foundUsers == null || foundUsers.isEmpty()) {
return false;
}
User foundUser = foundUsers.get(0);
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
md.update(password.getBytes());
byte[] encoded = md.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < encoded.length; i++) {
sb.append(Integer.toString((encoded[i] & 0xff) + 0x100, 16).substring(1));
}

if (sb.toString().equals(foundUser.getPassword())) {
return true;
}

return false;
}

[/code]

Leave a Reply

Your email address will not be published. Required fields are marked *