Search code examples
javacryptographypasswordspbkdf2

Checking user password on Android


I'm writing a utility class for password security for an Android app I'm working on. Currently, it generates a salt, then generates a hash using that salt and the password as parameters. I need a method that compares the hash stored in the database to the hash that is created when the user attempts to sign in. Should I compare the two byte arrays using Arrays.equals()? Or should I take in a byte[] dbHash, String password, and byte[] salt as parameters and go from there?

Here's the code so far.

package fitfast.security;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
import java.util.Arrays;

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

public final class Authenticator {

    private static final int length = 512;
    private static final int iterations = 60000;

    public static byte[] generateHash(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
        String algorithm = "PBKDF2WithHmacSHA512";
        KeySpec sp = new PBEKeySpec(password.toCharArray(), salt, iterations, length);
        SecretKeyFactory kf = SecretKeyFactory.getInstance(algorithm);
        return kf.generateSecret(sp).getEncoded();
    }

    public static byte[] generateSalt() throws NoSuchAlgorithmException {
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        byte[] salt = new byte[8];
        sr.nextBytes(salt);
        return salt;
    }

    public static boolean check(byte[] hash, String password, byte[] salt) {

        //code goes here

    }

}

Solution

  • I would say that Arrays.equals() would be the way to go. Something like

    public static boolean check(byte[] hash, String password, byte[] salt) {
    
       return Arrays.equals(hash, generateHash(password,salt));
    
    }