[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

		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));
		}

Here’s a complete example:

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;
	}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s