Why would this init succeed:
Cipher AESCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
AESCipher.init(Cipher.ENCRYPT_MODE, secretKey, secRandom);
while this fails:
Cipher AESCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
AESCipher.init(Cipher.DECRYPT_MODE, secretKey, secRandom);
Throwing an Exception in thread "main" java.security.InvalidKeyException: Parameters missing
The secretKey is generated by a KeyGenerator, and the secureRandom by SecureRandom.getInstance("SHA1PRNG") with a random static seed set.
Thanks
As correctly surmised by CodeInChaos, the SecureRandom instance is used to derive a random IV when the AESCipher
instance is created with Cipher.ENCRYPT_MODE
. However, you supply it as a parameter when creating a Cipher instance in decrypt mode. This little pointless code fragment shows an example.
public static void main(String[] args) throws Exception {
SecureRandom secRandom = SecureRandom.getInstance("SHA1PRNG");
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128, secRandom);
Key secretKey = kg.generateKey();
Cipher AESCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
AESCipher.init(Cipher.ENCRYPT_MODE, secretKey, secRandom);
IvParameterSpec iv = new IvParameterSpec(AESCipher.getIV());
AESCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
AESCipher.init(Cipher.DECRYPT_MODE, secretKey,iv, secRandom);
}
Also, your claim that you are initializing your SecureRandom instance with a static seed suggest a misunderstanding of that class. SecureRandom does not guarantee that you will get the same output when you provide the same seed. If you look carefully at the Javadocs you'll see that it attempts to provide some true entropy from other sources if at all possible.
EDIT 1:
Thanks to owlstead for his usual thoroughness in reviewing answers. See his answer to a related question for additional discussion. The source code for the SHA1PRNG is available online here. It is a little tricky to follow but if you provide a seed before asking the instance for any random bytes then the output will be completely deterministic. So my earlier statement is incorrect.
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