Question

I am working on a Java project where I must ensure the confidentiality of users password saved in a plaintext file.

To do so, I will write only a hash of the password in the file. More specifically, my intention is to write the hash of the password and a random salt, plus the random salt itself, to avoid the use of rainbow and lookup tables. I also want to use key-stretching with PBKDF2, to make the computation of the hash computationally expensive. Finally, I would like to use a keyed hash algorithm, HMAC, for a final layer of protection.

I am trying to implement my thoughts in a Java code, and I have found some examples of the operations that I have presented above:

private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes)
    throws NoSuchAlgorithmException, InvalidKeySpecException
{
    PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
    SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    return skf.generateSecret(spec).getEncoded();
}

The thing that I really cannot understand is how to input my secret key as the key used by the HMAC algorithm, as it doesn't seem an input to the function. I have looked through the Java documentation, but I cannot find a solution to my question.

Was it helpful?

Solution

If your talking about the HMAC function used internally by PBKDF2 for key streching, you don't need to supply a key, it will create one from the inputs.

If you wanted to use PBKDF2 to create key material for an HMAC function, then below works.

You init a Mac function the same way you'd do it with a cipher.

Using your pbkdf2 method above.

byte[] key = pbkdf2(password, salt, 1000, 16)
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(new SecretKeySpec(key, "HmacSHA1");

byte[] macResult = mac.doFinal(...);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top