Skip to content

Instantly share code, notes, and snippets.

@jnizet
Created February 10, 2014 21:08
Show Gist options
  • Save jnizet/8924228 to your computer and use it in GitHub Desktop.
Save jnizet/8924228 to your computer and use it in GitHub Desktop.
@Override
public boolean login(User user) {
// Check if we have a valid user/pass pair
String hashedPassword = hash(user.getPassword());
String jpql = "SELECT u FROM User u WHERE u.username=:userName AND u.password=:password";
TypedQuery<User> query = entityManager.createQuery(jpql, User.class);
query.setParameter("userName", user.getUsername());
query.setParameter("password", hash);
List<User> users = query.getResultList();
return !users.isEmpty();
}
private String hash(String password) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(tohash.getBytes());
byte[] bytes = md.digest();
return toHex(bytes);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
private String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment