我的Java类有额外的信用分配问题。目标是在没有密码的情况下解密文件。它使用PBEWithSHA1AndDESede算法加密,密码是没有数字或特殊字符的字典单词。
我试图解决这个问题的方法是一遍又一遍地猜测密码,直到我使用下面的代码做到正确。
我遇到的问题是在for循环的第一个循环之后输出extra_out.txt文件,当我希望只有在猜到正确的单词时才输出它。
因此,当它运行时,我得到异常“加密错误”,然后输出extra_out.txt文件(仍然加密),然后再输出9999“加密错误。”
非常感谢任何有用的建议!
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();
Random numGen = new Random();
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);
}
for(int i = 0; i < 10000; i++){
int rand = Math.abs(numGen.nextInt(words.size()));
File fileIn = new File("extracredit.enc");
File fileOut = new File("extra_out.txt");
String password = words.get(rand);
crackFile(fileIn, fileOut, password);
}
}
public static void crackFile(File input, File output, String password) {
try{
Crypt c = new Crypt(password);
byte[] bytes = FileIO.read(input);
FileIO.write(output, c.decrypt(bytes));
}
catch (IOException e) {
System.out.println("Could not read/write file");
}
catch (Exception e) {
System.out.println("Encryption error");
}
}
}