gpt4 book ai didi

Java:未捕获故意的 BadPaddingException

转载 作者:行者123 更新时间:2023-12-02 11:55:50 25 4
gpt4 key购买 nike

我的应用程序提示用户输入用于加密控制文件的密码。如果输入了错误的密码,应用程序将通过创建新的控制文件进行响应。因此,我需要捕获 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 之后没有其他内容可捕获。

关于Java:未捕获故意的 BadPaddingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47608965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com