Exceptions that have been extended from GeneralSecurityException
, including NoSuchPaddingException
and NoSuchAlgorithmException
are checked exceptions. Checked exceptions are exceptions that must be handled in Java. You can handle exceptions in multiple ways:
- Add a
throws
clause to your method; - Catch it and wrap a
RuntimeException
around it, using the original as cause (basically upgrading the exception in such a way that does not have to be handled, normally resulting in application failure); - Catch it, do something useful with it and simply move on.
In general, for NoSuchAlgorithmException
and NoSuchPaddingException
you upgrade the exception to a RuntimeException
such as IllegalStateException
. Normally your algorithm string stays static, and Java runtime environments are required to support "AES/CBC/PKCS5Padding"
so this exception only occurs if something is terribly wrong.
You can either catch GeneralSecurityException
or use a multi catch clause if you don't want to handle these exceptions separately. BadPaddingException
and IllegalBlockSizeException
during the decryption methods indicates a input failure and should therefore be handled separately (and keep in mind padding oracle attacks).
Note that Jython, as a different language, does not use checked exceptions so the exceptions simply fall through and cause program failure...
Example:
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
} catch(GeneralSecurityException e) {
throw new IllegalStateException("Could not retrieve AES cipher", e);
}