Skip to main content

Password Hash

Posted by evanx on February 21, 2007 at 11:40 PM PST

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

WARNING: This is an old defunct article (from February 2007) that doesn't include salt! It has been superceded by https://code.google.com/p/vellum/wiki/PasswordSalt (published December 2012).

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