Question

I'm not very experienced with Java, so this may be a nooby question. I was trying to experiment a bit with Java encryption, but for some reason I can't get an instance of Cipher. I always get a NoSuchPaddingException on this line, changing the padding to something else, like "/NoPadding" doesn't work:

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

Trying to run the code even though Eclipse says it's wrong results in this error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
Unhandled exception type NoSuchAlgorithmException
Unhandled exception type NoSuchPaddingException

at Encryption.main(Encryption.java:10)

What could be the problem? Do I have to import some certain things? In the current code I import javax.crypto.Cipher and javax.crypto.spec.SecretKeySpec.

When I use Jython the code works by the way.

Was it helpful?

Solution

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:

  1. Add a throws clause to your method;
  2. 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);
  3. 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);
} 

OTHER TIPS

The method which you are using throws Exception,so you need to handle that using try catch blocks,

use,

try{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
}

catch(Exception e){
    //print some thing
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top