Skip to main content

Password Hash

Posted by evanx on February 22, 2007 at 2:40 AM EST

Passwords should never be seen in clear text eg. in transfer objects, or in database columns. So we hash them up. Nothing to it.


Code Snippet

public class PasswordHasher {
    String algorithm = "SHA-256";
    
    public String hashPassword(byte[] passwordBytes) 
    throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance(algorithm);
        byte[] hashBytes = digest.digest(passwordBytes);
        String hashString = Base64.encode(hashBytes);
        return hashString;
    }
    
    public boolean verifyPassword(byte[] passwordBytes, String hashString) 
    throws NoSuchAlgorithmException {
        return hashPassword(passwordBytes).equals(hashString);
    }
}