This, pretty basic, piece of code is quite common when handling encryption\decryption in Java.
final Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
You indicated the following exceptions:
NoSuchPaddingException, NoSuchAlgorithmException InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException
Now all of these are
GeneralSecurityException's, so it would be easy to catch them all. But looking at the use case, you probably don't want to do that.
If you look at the cause of the exceptions then you will find that any of these exceptions - except for the last two - are only thrown when generating an implementation of an algorithm or a key. I think it is reasonable that once you have tested your application that these values remain more or less static. Hence it would be logical to throw - for instance - an
IllegalStateException is a runtime exception which you are not required to throw or catch. Of course, you should indicate the security exception as being the cause of the exception.
Now the last two exceptions,
IllegalBlockSizeException are different. They depend on the actual ciphertext, so they are dependent on the input of the algorithm. Now normally you should always verify the integrity of the input before you feed it into your
Cipher instance, initiated for decryption, for instance by first validating a HMAC checksum). So in that sense you could still get away with a runtime exception. If you don't check for integrity you should do something different with the exception, such as re-throwing it as a (different?) checked exception. If you take that route you should understand about e.g. padding oracle attacks.
It is probably best to use separate
catch blocks for the construction and initialization of the
Cipher and the decryption itself. You could also catch the exceptions
IllegalBlockSizeException before handling the
GeneralSecurityException. Starting with Java 7 you may use multi-catch statements as well (e.g.
catch(final BadPaddingException | IllegalBlockSizeException e)).
Finally some notes:
IllegalBlockSizeExceptionmay be created because of attacks or because the data was not completely present.