How to Securely Store Passwords in Java

One of the common requirements in Java web application is the secure storage of user passwords. You should never store user passwords in plain text. Passwords must be stored in such a way that there should be no way of getting the original password from the stored representation. Cryptographic one way hash functions are perfect for this purpose. Same hash is generated for the same password, but the original password cannot retrieved from the hash alone.

There are a number of common hash functions in use such as MD5, SHA1, SHA256 etc. I have also seen many implementations using them directly for password storage. However these are not suitable for password hashes due to a number of reasons - the algorithms such as SHA256 are too fast and hence brute forcing the hash is easy. Using MD5 hash without a salt is almost as bad as storing plain text passwords!

There are a number of hash functions specifically designed for storing hashed passwords. These include PBKDF2, bcrypt, scrypt etc. PBKDF2 is an excellent hash algorithm for password hashing and is one of the NIST recommended algorithms.

Verifiers SHALL store memorized secrets in a form that is resistant to offline attacks. Secrets SHALL be hashed with a salt value using an approved hash function such as PBKDF2 as described in [SP 800-132]. The salt value SHALL be a 32-bit or longer random value generated by an approved random bit generator and stored along with the hash result. At least 10,000 iterations of the hash function SHOULD be performed. A keyed hash function (e.g., HMAC [FIPS198-1]), with the key stored separately from the hashed authenticators (e.g., in a hardware security module) SHOULD be used to further resist dictionary attacks against the stored hashed authenticators.

One of the issues with hash functions is that they are susceptible to rainbow table attack. This attack can be prevented by using a salt text (a random text) along with each password before hashing it. This ensures that even when two different users use the same password, the hash values stored are different.

The following Java program demonstrates the use of PBKDF2 hash algorithm with salt text for storing passwords. It uses NIST recommended specification. The following example will run on Java SE 8 or above. If you want to use it Java 7 or below replace the Base64 class with Apache commons codec Base64 class.

Please note that the salt stored for the user must be changed when password is updated.

import java.security.SecureRandom;
import java.security.spec.KeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class SecurePasswordStorageDemo {

    // Simulates database of users!
    private Map<String, UserInfo> userDatabase = new HashMap<String,UserInfo>();

    public static void main(String[] args) throws Exception {
        SecurePasswordStorageDemo passManager = new SecurePasswordStorageDemo();
        String userName = "admin";
        String password = "password";
        passManager.signUp(userName, password);

        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter username:");
        String inputUser = scanner.nextLine();

        System.out.println("Please enter password:");
        String inputPass = scanner.nextLine();

        boolean status = passManager.authenticateUser(inputUser, inputPass);
        if (status) {
            System.out.println("Logged in!");
        } else {
            System.out.println("Sorry, wrong username/password");
        }
        scanner.close();
    }

    private boolean authenticateUser(String inputUser, String inputPass) throws Exception {
        UserInfo user = userDatabase.get(inputUser);
        if (user == null) {
            return false;
        } else {
            String salt = user.userSalt;
            String calculatedHash = getEncryptedPassword(inputPass, salt);
            if (calculatedHash.equals(user.userEncryptedPassword)) {
                return true;
            } else {
                return false;
            }
        }
    }

    private void signUp(String userName, String password) throws Exception {
        String salt = getNewSalt();
        String encryptedPassword = getEncryptedPassword(password, salt);
        UserInfo user = new UserInfo();
        user.userEncryptedPassword = encryptedPassword;
        user.userName = userName;
        user.userSalt = salt;
        saveUser(user);
    }

    // Get a encrypted password using PBKDF2 hash algorithm
    public String getEncryptedPassword(String password, String salt) throws Exception {
        String algorithm = "PBKDF2WithHmacSHA1";
        int derivedKeyLength = 160; // for SHA1
        int iterations = 20000; // NIST specifies 10000

        byte[] saltBytes = Base64.getDecoder().decode(salt);
        KeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, iterations, derivedKeyLength);
        SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm);

        byte[] encBytes = f.generateSecret(spec).getEncoded();
        return Base64.getEncoder().encodeToString(encBytes);
    }

    // Returns base64 encoded salt
    public String getNewSalt() throws Exception {
        // Don't use Random!
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        // NIST recommends minimum 4 bytes. We use 8.
        byte[] salt = new byte[8];
        random.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt);
    }

    private void saveUser(UserInfo user) {
        userDatabase.put(user.userName, user);
    }

}

// Each user has a unique salt
// This salt must be recomputed during password change!
class UserInfo {
    String userEncryptedPassword;
    String userSalt;
    String userName;
}