as a second rule,
2. Catch specific exceptions
By catching (java.lang.)Exception, you also catch things like IndexOutOfBoundsException, NegativeArraySizeException, NoSuchElementException, IOException and others that have nothing to do (at least, not directly) with the code in the try-block. Especially in the case of an empty catch-block, lots of problems that are neatly reported by java are silently ignored, causing
Nothing is displayed after i execute the program.
For example, you might have a wrong key size causing a InvalidKeyException:
java.security.InvalidKeyException: Wrong key size
at javax.crypto.spec.DESKeySpec.<init>(DashoA13*..)
at javax.crypto.spec.DESKeySpec.<init>(DashoA13*..)
at etc.
If plainText is null, you get
Exception in thread "main" java.lang.IllegalArgumentException: Null input buffer
at javax.crypto.Cipher.doFinal(DashoA13*..)
at etc.
-
try {
-
// making this null causes an IllegalArgumentException
-
byte[] plainText = new byte[]{0x38,0x39};
-
// making this shorter causes an InvalidKeyException
-
byte[] key = new byte[]{0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37};
-
byte[] cipherText = null;
-
//init cipher
-
KeySpec ks = new DESKeySpec(key);
-
SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
-
SecretKey ky = kf.generateSecret(ks);
-
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
-
cipher.init(Cipher.ENCRYPT_MODE, ky);
-
//encrypt
-
cipherText = cipher.doFinal(plainText);
-
System.out.println("Key: " + new String(key));
-
System.out.println("PlainText:" + new String(plainText));
-
//display cipherText
-
System.out.println("CipherText: " + byte2Hex(cipherText));
-
} catch (InvalidKeyException e) {
-
e.printStackTrace();
-
} catch (NoSuchAlgorithmException e) {
-
e.printStackTrace();
-
} catch (InvalidKeySpecException e) {
-
e.printStackTrace();
-
} catch (NoSuchPaddingException e) {
-
e.printStackTrace();
-
} catch (IllegalBlockSizeException e) {
-
e.printStackTrace();
-
} catch (BadPaddingException e) {
-
e.printStackTrace();
-
}
-
3. System.out.println for byte[]
This actually prints a java object pointer on the console:
System.out.println("Key: " + key);
for example might print
Key: [B@c7e553
Using a special routine like byte2Hex is a solution, otherwise, you might use
- System.out.println("Key: " + new String(key));
as a quick workaround.