Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my AES Cipher throw an InvalidKeyException on init of DECRYPT_MODE

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

like image 248
user54000 Avatar asked Jan 02 '13 15:01

user54000


1 Answers

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.

like image 176
President James K. Polk Avatar answered Nov 15 '22 01:11

President James K. Polk