我的xor加密不适用于复杂文件

时间:2012-06-13 00:07:33

标签: java encryption xor

为了好玩,我一直在尝试制作一个文件加密器,它对128位密钥进行按位xor加密。它似乎适用于使用某些编辑器的纯文本文件,但对于其他和更复杂的文件,我遇到“损坏的文件”错误。如果我对文本文件进行两次加密,在Gedit中它会显示原始文件的内容,但在记事本中,我只是得到了一大堆问号。

我用Java编写了这段代码,但加密部分非常普遍。密钥的形式为8个16位字符:

char[] key = {26372, 15219, 53931, 50406, 26072, 23469, 25002, 37812};

要加密文件,我有一个运行此代码的循环:

builder.append((char)(bR.read() ^ key[pos++]));
if(pos == 8) pos = 0; //returns to first position in key

这将使用BufferedReader从文件中读取下一个字符,将其与键中的下一个字符进行xors并将其附加到StringBuilder。

以下是整个代码:

import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;


public class Encryptor implements Runnable {

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            SwingUtilities.invokeAndWait(new Encryptor());
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    JFrame frame;
    JButton bCancel, bEncrypt;
    JTextArea statusArea;
    JScrollPane statusScroll;
    JProgressBar progressBar;
    String fileContents, fileType, fileName;
    EncryptSwingWorker encryptWorker;
    char[] key = {
        26372, 15219, 53931, 50406, 26072, 23469, 25002, 37812};

    public void run() {

        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch(Exception e) {}

        frame = new JFrame();

        statusArea = new JTextArea();
        statusArea.setEditable(false);
        statusScroll = new JScrollPane(statusArea);
        progressBar = new JProgressBar();
        progressBar.setValue(0);

        bCancel = new JButton("Cancel");
        bCancel.setEnabled(false);
        bCancel.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                int option = JOptionPane.showOptionDialog(frame,
                        "Are you sure you want to cancel?",
                        "Warning", JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE, null,
                        null, null
                );
                if(option == 0) {
                    encryptWorker.cancel(true);
                    statusArea.append("Encryption cancelled\n");
                    progressBar.setValue(0);
                    progressBar.setIndeterminate(false);
                    bCancel.setEnabled(false);
                    bEncrypt.setEnabled(true);
                }
            }

        });
        bEncrypt = new JButton("Encrypt file...");
        bEncrypt.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                encryptWorker = Encryptor.this.new EncryptSwingWorker();
                encryptWorker.execute();
            }

        });

        JPanel top = new JPanel(new BorderLayout());
        top.add(bEncrypt, BorderLayout.CENTER);
        top.add(bCancel, BorderLayout.EAST);
        frame.getContentPane().add(top, BorderLayout.NORTH);
        frame.getContentPane().add(statusScroll, BorderLayout.CENTER);
        frame.getContentPane().add(progressBar, BorderLayout.SOUTH);

        frame.setSize(200, 150);
        frame.setResizable(false);
        frame.setTitle("sEncryptor");
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setIconImage(Toolkit.getDefaultToolkit().getImage("encryptor.png"));
    }

    void encrypt() throws IOException {
        JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(frame);

        if(returnVal == JFileChooser.APPROVE_OPTION) {
            if(fc.getSelectedFile() == null) {
                JOptionPane.showOptionDialog(frame,
                    "You did not select a file",
                    "File Open Error",
                    JOptionPane.DEFAULT_OPTION,
                    JOptionPane.WARNING_MESSAGE, null,
                    null, null
                );
                encrypt();
                return;
            }

            bCancel.setEnabled(true);
            bEncrypt.setEnabled(false);

            fileName = fc.getSelectedFile().getPath();

            statusArea.append("Calculating size...\n");
            progressBar.setIndeterminate(true);
            int size = (int)(new File(fileName).length() / 32);
            progressBar.setIndeterminate(false);
            progressBar.setMaximum(size);

            BufferedReader bR = new BufferedReader(new FileReader(fc.getSelectedFile()));
            StringBuilder builder = new StringBuilder();

            statusArea.append("Encrypting...\n");
            int pos = 0;
            for(double d = 0; bR.ready(); d += 0.03125) {
                if(encryptWorker.isCancelled()) return;
                progressBar.setValue((int)d);
                builder.append((char)(bR.read() ^ key[pos++]));
                if(pos == 8) pos = 0;
            }

            progressBar.setValue(0);
            progressBar.setIndeterminate(true);

            fileContents = builder.toString();
            bR.close();
            statusArea.append("Encryption finished\n");
            progressBar.setIndeterminate(false);
        }
    }

    void save(String file) throws IOException {
        statusArea.append("Saving...\n");
        progressBar.setIndeterminate(true);
        BufferedWriter bW = new BufferedWriter(new FileWriter(file));
        bW.write(fileContents);
        bW.close();
        progressBar.setIndeterminate(false);
        statusArea.append("Done!\n");
    }

    void saveAs() throws IOException {
        JFileChooser fc = new JFileChooser();
        int returnVal = fc.showSaveDialog(frame);

        if(returnVal == JFileChooser.APPROVE_OPTION) {
            if(fc.getSelectedFile() == null) {
                JOptionPane.showOptionDialog(frame,
                    "You did not select a file",
                    "File Open Error",
                    JOptionPane.DEFAULT_OPTION,
                    JOptionPane.WARNING_MESSAGE, null,
                    null, null
                );
                saveAs();
                return;
            }

            save(fc.getSelectedFile().getPath());
        }
    }

    class EncryptSwingWorker extends SwingWorker<Void, Void> {

        @Override
        protected Void doInBackground() throws Exception {
            encrypt();
            if(EncryptSwingWorker.this.isCancelled()) return null;
            bCancel.setEnabled(false);
            while(true) {
                Object[] options = {"Override", "Save As...", "Cancel"};
                int option = JOptionPane.showOptionDialog(frame,
                        "Override existing file?",
                        "Save", JOptionPane.YES_NO_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE, null,
                        options, options[0]
                );
                if(option == 0)
                    try {
                        save(fileName);
                    } catch(IOException e1) {
                        e1.printStackTrace();
                    }
                else if(option == 1)
                    try {
                        saveAs();
                    } catch(IOException e1) {
                        e1.printStackTrace();
                    }
                else {
                    int option1 = JOptionPane.showOptionDialog(frame,
                            "The encryption will be lost if you continue\n" +
                            "Are you sure you want to cancel?",
                            "Warning", JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null,
                            null, null
                    );
                    if(option1 == 1) continue;
                    break;
                }
                break;
            }
            fileContents = "";
            bEncrypt.setEnabled(true);
            return null;
        }

    }
}

我的代码中是否缺少某些内容,或者整个文件的xored是否会导致问题?

1 个答案:

答案 0 :(得分:3)

知道了。问题在于文件编码,一如既往:)。从不永远,取决于默认编码 - 它最终会适得其反。

由于ReaderWriter类是针对纯文本输入/输出的,因此它会搞砸。在这种情况下,Writer不知道如何处理它获得的各种整数并最终失败。修复Writer后,您还必须修复Reader,因为加密数据可能不仅仅是有效字符...

最佳解决方案是忽略字符,使用字节和FileInputStreamFileOutputStream(必要时由Buffered兄弟包裹),因为这些是处理二进制数据。这样,您最终会完全读/写您想要读/写的数据。试着自己一起破解它,这是一个很好的教训。如果你遇到困难,请查看here

最简单解决方案是只更改两行。请注意,它将再次仅适用于文本文件!说真的,不要把随机数字和可打印的字符混在一起。

BufferedReader bR = new BufferedReader(new FileReader(fc.getSelectedFile()));

BufferedReader bR = new BufferedReader(new InputStreamReader(new FileInputStream(fc.getSelectedFile()), "UTF-8"));

BufferedWriter bW = new BufferedWriter(new FileWriter(file));

BufferedWriter bW = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));