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.
To derive the i
th 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With