PBKDF2 output size vs internal hashing algorithm PBKDF2 allows you to choose an output size as well as the internal hashing function used.

My question is, do these two sizes need to match?

For example, if I'm using PBKDF2 with SHA512, does my output size need to be 512 bits?

I'm a little confused because WebCrypto and CryptoJS allow you to specify SHA512 as the hashing algorithm, but then limit the output key size to the AES max output size, which is 256.

Why is AES even used to generate the final key, and not just a SHA hash of the derived key?
My question is, do these two sizes need to match?


Well, officially no, the output of PBKDF2 is only limited by the following definition from PKCS#5:

dkLen      intended length in octets of the derived
           key, a positive integer, at most
           (2^32 - 1) * hLen


There hLen is the length of the internal hash algorithm.

PBKDF1 is actually limited to hLen - unless you are using the horrible Microsoft implementation which is simply completely insecure and unspecified for anything over hLen of output.

It is however strongly recommended to keep to hLen as output. The reason for this is not that the output is somehow dependent. The problem is that the whole work factor (parameterized by the iteration count) is repeated for each additional block that is required. The problem with this is that attackers do often not need to perform all these additional operations to verify correctness of the input while brute forcing or performing a dictionary attack. So additional output put you at a disadvantage over an attacker.

Try to keep to SHA-512 and a maximum output size of 512 bits or use an additional function such as HKDF to increase the amount of output (or use the KDF multiple times to derive multiple keys/secret values).




  Why is AES even used to generate the final key, and not just a SHA hash of the derived key?


This is a misconception on your part. AES may take the output of PBKDF2 to be an AES key. No AES key operations are however performed within PBKDF2 (AES has a block size of 128 so expecting 256 bytes of output would be strange anyway).

Directly converting the output to a key means that the user doesn't have to "manually" an AES key type from the output of the KDF. This is more secure as the bytes do not have to be copied into the resulting key - and the original bytes don't need to be destroyed (zeroed) either.

In case of hardware crypto the output of the KDF may be kept in the device as well (instead of first copying it to memory of the host device), although this is usually not an issue for PBKDF2 as password handling is usually not performed in specialized hardware.