Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can PBKDF2 using HMAC SHA-1 return more than 20 bytes?

If Node's crypto.PBKDF2 uses HMAC SHA-1, how can the key length ever be more than 20 bytes?

Here's what I understand (apparently incorrectly): crypto.PBKDF2(password, salt, iterations, keylen, callback) uses HMAC SHA-1 to hash a password with a salt. Then it takes that hash and hashes it with the same salt. It repeats that for however many iterations you tell it and then passes you back the result. The result is truncated to the number of bytes you specified in keylen.

SHA-1 outputs 160 bits, or 20 bytes. However, I can ask for keylen more than 20 bytes from crypto.PBKDF2, and past the 20th byte, the data doesn't repeat. That doesn't make sense to me.

What am I misunderstanding here?

Try it out:

c.pbkdf2('password', 'salt', 1, 21, function(err, key) {
    for (var i = 0; i < key.length; i++) {
        console.log(key[i].toString(36));
    }
});

I would expect to see some kind of pattern after the 20th byte, but I don't.

like image 971
Mike M. Lin Avatar asked Jan 18 '13 08:01

Mike M. Lin


1 Answers

To derive the ith block, PBKDF2 runs the full key derivation, with i concatenated to the salt. So to get your 21st byte, it simply runs the derivation again, with a different effective salt, resulting in completely different output. This means deriving 21 bytes is twice as expensive as deriving 20 bytes.


I recommend against using PBKDF2 to derive more than the natural output size/size of the underlying hash. Often this only slows down the defender, and not the attacker.

I'd rather run PBKDF2 once to derive a single master key, and then use HKDF to derive multiple secrets from it. See How to salt PBKDF2, when generating both an AES key and a HMAC key for Encrypt then MAC? on crypto.SE

like image 141
CodesInChaos Avatar answered Oct 11 '22 12:10

CodesInChaos