Why does PBE generate the same key with different numbers of salts and iterations?

I am trying to verify PBE encryption / decryption. I found that PBE generates the same key with different amounts of salt and iterations. Of course, the password is used the same way. As I understand it, the same password and a different salt / iteration should have different keys. Below is my test code:

import java.security.Key; import java.security.SecureRandom; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; public class PBETest { public static void main(String[] args) throws Exception { String algo = "PBEWithSHA1andDESede"; System.out.println("====== " + algo + " ======"); char[] password = "password".toCharArray(); SecureRandom rand = new SecureRandom(); byte[] salt = new byte[32]; rand.nextBytes(salt); int iterationCount = rand.nextInt(2048); //encryption key PBEKeySpec encPBESpec = new PBEKeySpec(password, salt, iterationCount); SecretKeyFactory encKeyFact = SecretKeyFactory.getInstance(algo); Key encKey = encKeyFact.generateSecret(encPBESpec); System.out.println("encryptioin iteration: " + iterationCount); //decryption key rand.nextBytes(salt); iterationCount = rand.nextInt(2048); PBEKeySpec decPBESpec = new PBEKeySpec(password, salt, iterationCount); SecretKeyFactory decKeyFact = SecretKeyFactory.getInstance(algo); Key decKey = decKeyFact.generateSecret(decPBESpec); System.out.println("decryptioin iteration: " + iterationCount); System.out.println("encryption key is same as decryption key? " + encKey.equals(decKey)); } } 

I expect the final output to be false . Did I do something wrong?

+7
source share
2 answers

You turned out spectacularly lucky, and your random salts and iterations match, just match. Go straight to Las Vegas. Now.;)

I googled for PBEWithSHA1andDESede and tracked this example: http://cryptofreek.org/2010/06/04/encrypting-and-decrypting-files-with-java in which it sets the key with only new PBEKeySpec(password) and creates a separate PBEParameterSpec using the amount of salt and iteration, which is then passed to Cipher.init ().

So, no, you didn’t do anything wrong, you just stopped before the salt and the bill got into the code.

+4
source

If you use PBKDF2WithHmacSHA1 instead of PBEWithSHA1andDESede , your guess works because it supports salt. You just need to add the keyLength parameter to PBEKeySpec :

  String algo = "PBKDF2WithHmacSHA1"; 

...

  PBEKeySpec decPBESpec = new PBEKeySpec( password, salt, iterationCount, 128 ); 

I checked the test and the result is false .

However, note that for the encryption and decryption to work correctly, you need to use the same solon and iteration counter when generating the key.

+3
source

All Articles