我有一个应用程序来使用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();
}
}
};
});
}
}
答案 0 :(得分:0)
您有两个输入二进制文件:密钥文件和纯文本文件。你有一个输出文件,你编写的密文文件,也是二进制文件。密钥文件必须至少与明文文件一样长。
repeat
p <- read byte from plaintext binary file
k <- read byte from key binary file
c <- p XOR k
write byte c to cyphertext binary file
until all bytes read from plaintext file
你说你以前的努力使用过文本文件。请注意,Java使用不同的方法来读取/写入二进制文件和文本文件。在二进制文件上使用文本方法,或者反之亦然,将得到不正确的结果。