我尝试自己解决此问题,但似乎找不到解决方法。我正在使用Java AES遍历文件夹中的所有文件来加密文件夹。现在,我还想对所选文件夹内的文件夹内的文件进行加密,有人可以帮忙吗?
这是我用于遍历所选文件夹的代码。
Arrays.asList(filelist).forEach(file -> {
try {
encrypting = fileProcessor(Cipher.ENCRYPT_MODE, FolderKey.getText(), file, file);
FolderProgress.progressProperty().unbind();
FolderProgress.progressProperty().bind(encrypting.progressProperty());
encrypting.messageProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
System.out.println(newValue);
}
});
new Thread(encrypting).start();
} catch (InvalidKeyException e) {
//Dsiplay error message if the key is wrong.
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Incorrect password!");
alert.showAndWait();
System.err.println("Couldn't encrypt " + file.getName() + ": " + e.getMessage());
}
});
这是加密方法:
public Task fileProcessor(int cipherMode, String key, File inputFile, File outputFile) {
return new Task() {
@Override
protected Object call() throws Exception {
try {
Key secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(cipherMode, secretKey);
//getting ourr input file in bytes.
FileInputStream inputStream = new FileInputStream(inputFile);
byte[] inputBytes = new byte[(int) inputFile.length()];
inputStream.read(inputBytes);
byte[] outputBytes = cipher.doFinal(inputBytes);
//Writing out to our output file
FileOutputStream outputStream = new FileOutputStream(outputFile);
outputStream.write(outputBytes);
//clossing the input and output streams.
inputStream.close();
outputStream.close();
//This for loop is for our progress indicator, it sleeps for half a second for each loop
//Thus it takes it 5 secs to complete the loop and our task.
for (int i = 0; i < 10; i++) {
//sleep for 5 secs.
Thread.sleep(500);
updateMessage("500 milliseconds");
//update the progress.
updateProgress(i + 1, 10);
}
} catch (NoSuchPaddingException | NoSuchAlgorithmException
| InvalidKeyException | BadPaddingException
| IllegalBlockSizeException | IOException e) {
e.printStackTrace();
} catch (java.security.InvalidKeyException ex) {
//Dsiplaying error message if the kkey entered is wrong.
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Incorrect password!");
alert.showAndWait();
Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
}
return true;
}
};
}