0
votes

I am trying to implement AES custom password encryption and would like to understand the codes below.

I don't quite understand why is there a need to specify the key size 256 "PBEKeySpec(password, salt, 65536, 256)", when I have used "PBKDF2WithHmacSHA256" which suppose to generate the SecretKey as 256 bits.

And after generating the key using my password+salt, why do I need to associate it with the SecretKeySpec as AES algorithm.

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
1
To be clear: you're asking about password-based encryption where a password is used to derive a key which is then used to encrypt some other data and not about encrypting passwords themselves, right?Artjom B.
@ArtjomB. yes. I am trying to implement a password based encryption. And I think I have another problem is to encrypt this "password", which is used to encrypt the data.ilovetolearn

1 Answers

4
votes

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.