0

我的应用程序提示用户输入用于加密控制文件的密码。如果输入了错误的密码,应用程序会通过创建一个新的控制文件来做出响应。因此我需要捕获一个 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)
4

1 回答 1

1

CipherInputStream.read(您的第 197 行) throws IOException, not BadPaddingException,因此异常被后续catch (IOException ex).

之后你没有明确地抛出其他异常,所以没有什么可以捕捉 after decryptHashFile

于 2017-12-02T14:58:10.730 回答