Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PBKDF2 with HMAC in Java

I am working on a Java project where I must ensure the confidentiality and integrity 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.

At this point, I am not really sure if I understood correctly how the different part of the encryption mechanism work, so I would accept any help on the topic.

like image 364
papafe Avatar asked Nov 08 '13 15:11

papafe


1 Answers

I think I see the confusion. You're apparently expecting your code to apply PBKDF2 then HMAC-SHA-1. That's not how it works: HMAC-SHA-1 is used inside PBKDF2.

The gist of PBKDF2 is to apply a function repeatedly which has the following properties:

  • it takes two arguments;
  • it returns a fixed-size value;
  • it is practically undistinguishable from a pseudo-random function.

HMAC-SHA-1 is such a function, and a common choice. There are other variants of PBKDF2, using HMAC-MD5, HMAC-SHA-256, or other functions (but these variants aren't in the basic Java library).

PBKDF2 takes two data inputs (plus some configuration inputs): the password, and a salt. If you want to include a secret value in the calculation, PBKDF2's input is the place for it: don't tack on a custom scheme on top of that (doing your own crypto is a recipe for doing it wrong). Append the pepper (secret value common to all accounts) to the salt (public value that varies between accounts).

Note that pepper is of limited usefulness. It's only useful if the hashes and the pepper secret value are stored in different places — for example, if the hashes are in a database and the pepper is in a disk file that is not directly vulnerable to SQL injection attacks.

like image 66
Gilles 'SO- stop being evil' Avatar answered Nov 14 '22 23:11

Gilles 'SO- stop being evil'