Search code examples
javacryptographypbkdf2secret-key

PBKDF2 - What happens when generating 1024 bits key length with SHA512?


I have this code snippet to generate key with PBKDF2.

SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
        PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), iterations, length);
        SecretKey key = skf.generateSecret(spec);
        byte[] res = key.getEncoded();

I am wondering how generating works when a key lengthis longer than specified SHA digest algorithm type?

For example - what happens when I set a key length of 1024 bits and use PBKDF2WithHmacSHA512 algorithm? Where are 512 bits generated?


Solution

  • In general it is not advised to ask for more than the hash length as each block is run through all the iterations again:

    According to Wikipedia (which has a somewhat more readable format than PKCS#5):

    DK = T1 || T2 || ... || Tdklen/hlen
    Ti = F(Password, Salt, c, i)
    

    here c is the iteration count by the way.

    The problem with this is that generally large amounts of key material are only used when the result is split into multiple components. And if an attacker can verify a good password guess using only - say - the first 128 bits then the attacker has to do less work than the legitimate user of the algorithm.

    One way of resolving this is to split the output of PBKDF2 using a KBKDF such as HKDF using different labels (information that is also hashed). That way you can generate almost infinite amount of key material without running through all the iterations for each 512 bits.

    Note that 512 bits is enough for two very secure AES-256 bit keys. So that's one very good reason to use SHA-512 for PBKDF2. Note that on 64 bit machines SHA-512 may be faster than SHA-256 while delivering more output material and security.