Java:没有捕获故意的BadPaddingException

时间:2017-12-02 14:34:12

标签: java try-catch badpaddingexception

我的应用会提示用户输入用于加密控制文件的密码。如果输入了错误的密码,应用程序将通过创建新的控制文件进行响应。因此,我需要捕获BadPaddingException,以便触发相应的响应。

这是应该生成异常的代码段

private void existingHashFile(String file) {
        psUI = new passwordUI(new javax.swing.JFrame(), true, "existing");
        psUI.setVisible(true);
        this.key = passwordUI.key;
        try {
            hash.decryptHashFile(file, this.key); //this is line 240
        } catch (BadPaddingException ex) {
            Logger.getLogger(homePage.class.getName()).log(Level.SEVERE, null, ex);
            //then the file was not decrypted
            System.out.println("BPE 2!");
        } catch (Exception ex) {
            Logger.getLogger(homePage.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("BPE 3!");
        }

为了完整性,这里是上面调用的decryptHashFile方法

public void decryptHashFile(String filename, String key) throws BadPaddingException, UnsupportedEncodingException, Exception {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        CipherInputStream cis = null;   
        String outFile = filename.replace(".enc", "");
        byte[] byteKey = key.getBytes("UTF-8");

        Cipher cipher = getCipher(byteKey, "decrypt");

        try {
            fis = new FileInputStream(filename);
            fos = new FileOutputStream(outFile);
            cis = new CipherInputStream(fis, cipher);
            byte[] buffer = new byte[1024];
            int read = cis.read(buffer);
            while (read != -1) {
                fos.write(buffer, 0, read);
                read = cis.read(buffer); //this is line 197
            }
        } catch (IOException  ex) {
            Logger.getLogger(hashListClass.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fos != null) {
                fos.close();
            }
            if (cis != null) {
               cis.close(); 
            }
            if (fis != null) {
               fis.close(); 
            }
        }
    }

当我故意输入错误的密码时,我看到了这个堆栈跟踪,但是我的代码(我在示例中使用过println)没有被执行:

Dec 02, 2017 2:31:34 PM appwatch.hashListClass decryptHashFile
SEVERE: null
java.io.IOException: javax.crypto.BadPaddingException: Given final block not properly padded
    at javax.crypto.CipherInputStream.getMoreData(CipherInputStream.java:121)
    at javax.crypto.CipherInputStream.read(CipherInputStream.java:239)
    at javax.crypto.CipherInputStream.read(CipherInputStream.java:215)
    at appwatch.hashListClass.decryptHashFile(hashListClass.java:197)
    at appwatch.homePage.existingHashFile(homePage.java:240)

1 个答案:

答案 0 :(得分:1)

CipherInputStream.read(第197行)抛出IOException而不是BadPaddingException,因此后续catch (IOException ex)会抓住异常。

之后你没有明确地抛出其他异常,所以在decryptHashFile之后没有别的东西可以捕获。