好的,昨天我提交了 this关于我正在做的额外学分作业的问题。从那时起,我认为我已经取得了一些进步,但现在我遇到了一些新问题,我需要一些帮助。
正如我在上一篇文章中提到的,我的任务是解密加密文件。该文件已使用 PBEWithSHA1AndDESede 算法加密,但我们没有密码。密码是字典单词,不包含特殊字符或数字。此外,该文件使用未修改版本的 Crypt 类进行加密,链接如下。
我尝试处理这个问题的方法是通过暴力测试从字典中随机抽取的数千个单词。
这是我的新代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class WordGuess {
public static void main(String[] args) {
ArrayList<String> words = new ArrayList();
String curWord = "";
try {
File aFile = new File("english.txt");
Scanner reader = new Scanner(aFile);
while (reader.hasNext()) {
curWord = reader.next();
if (curWord.length() == 5) {
words.add(curWord);
}
}
}
catch (FileNotFoundException e) {
System.out.println("Error: " + e);
}
Random numGen = new Random();
int count = 0;
int maxTries = 10000;
int tries = 0;
File extraIn = new File("extracredit.enc");
File extraOut = new File("extra_out.txt");
while (true) {
try {
Crypt c = new Crypt(randomGenerator(words, numGen));
System.out.println(randomGenerator(words, numGen));
byte[] bytes = FileIO.read(extraIn);
System.out.println("Attempt number: " + tries++);
FileIO.write(extraOut, c.decrypt(bytes));
System.out.println("Success!");
}
catch (IOException e) {
System.out.println("Could not read/write file");
} catch (Exception e) {
if (++count == maxTries) {
try {
throw e;
} catch (Exception e1) {
System.out.println("Encryption error.");
System.exit(0);
}
}
}
}
}
public static String randomGenerator(ArrayList<String> w, Random i) {
return w.get(Math.abs(i.nextInt(w.size())));
}
}
代码似乎按预期运行,但是当我返回并查看控制台中的一些结果时,我看到随机的“成功!”尝试错误密码后的消息。我的问题是为什么代码能够在 System.out.println("Success!"); 之后继续运行线路能跑吗?我的印象是,如果密码猜对并且“成功!”,代码就会终止。显示消息是因为它不会抛出异常。
此外,在密码猜测失败时,代码仍然会写出一个文本文件。欢迎任何有关原因的想法!
再次,非常感谢任何有用的信息!这是 Crypt适合那些有兴趣自己运行代码的人。
最佳答案
打印成功消息后,程序将继续循环(while(true))。
为什么每次解密尝试都必须引发错误?
关于java - 暴力破解问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22855685/