我有一个使用 XOR 加密文本文件的应用程序。现在我需要修改它以使用另一个二进制文件(作为密钥)对二进制文件(如 jpegs)进行编码。我怎样才能做到这一点?它与二进制偏移量有什么共同点吗?我需要它用于学习目的。我的代码片段,负责文本加密:
动作类:
import javax.swing.JFileChooser;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Actions extends GuiElements {
final JFileChooser fc = new JFileChooser("D:");
final JFileChooser fc1 = new JFileChooser("D:");
public Actions() {
btnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Handle open button action.
if (e.getSource() == btnLoad) {
int returnVal = fc.showOpenDialog(Actions.this);
if (returnVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
String content = file.toString();
FileReader reader = null;
try{
reader = new FileReader(content);
}
catch (FileNotFoundException e1){
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(reader);
try{
textArea.read(br, null);
}
catch (IOException e1) {
e1.printStackTrace();
}
try{
br.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
textArea.requestFocus();
}
else{
}
}
}
});
btnCipher.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent click) {
String textToCipher = textArea.getText();
String cipherKey = textField.getText();
String cipheredText = "";
int xor;
char temp;
for (int i=0; i<textToCipher.length(); i++){
xor = textToCipher.charAt(i) ^ cipherKey.charAt(i % cipherKey.length());
temp = (char)xor;
cipheredText += temp;
}
textArea.setText(cipheredText);
}
});
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String textTosave = textArea.getText();
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("D:"));
int retrival = chooser.showSaveDialog(null);
if (retrival == JFileChooser.APPROVE_OPTION) {
try {
FileWriter fw = new FileWriter(chooser.getSelectedFile());
String cont = textArea.getText();
String content = cont.toString();
fw.write(content);
fw.flush();
fw.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
};
});
}
}