why is there a need to specify the key size 256
PBKDF2 is a flexible password-based key derivation function. It uses an underlying hash function with many iterations. It can output any size of key that you want. It is common to use SHA-256 even when generating AES-128 keys, because SHA-256 is not known to be broken and it is relatively slow compared to other hash functions such as MD5 and SHA-512 (only on x64). The slowness is an important factor for a PBKDF, because it directly impacts the attacker when they try to brute-force the password. Of course, you also have the adjustable iteration count.
Additionally, PBKDF2 can output even more key material than the underlying hash function output size. For example, it is common to request the output of PBKDF2 to include the IV. In your case, the output should be 384 bits long.
Generally, it is not recommended to request more than the underlying hash function from PBKDF2. You should use SHA-512 if you want to derive the IV, too. As long as the salt is randomly generated for each encryption and stored alongside the ciphertext, this should be enough to achieve semantic security.
So, to answer your question, PBKDF2 has no idea how you want to use the output. You are responsible for that. You have to know what you're doing. There are a million different ways to solve the PBKDF part of encrypting something.
why do I need to associate it with the SecretKeySpec as AES algorithm.
If you want encrypt something with AES using the Cipher
instance, you need to pass in a java.security.Key
object that would resolve to AES at runtime. The Key#getAlgorithm()
method is used for that. If you don't specify "AES"
when creating the SecretKeySpec
, you will get an InvalidKeyException
.