Java:没有抓住故意的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)

CipherInputStream.read(您的行197)抛出 IOException,而不是 BadPaddingException,因此例外被随后的 catch (IOException ex)捕获。

之后,您没有明确地抛出其他例外,因此decryptHashFile之后没有其他捕获。

相关内容

  • 没有找到相关文章

最新更新