Java语言实现文本文件的加密解密

2021年1月15日 17点热度 0条评论 来源: Doctor_96

主要实现从系统磁盘读取txt文本文件,然后以二进制转换为十六进制的方式对文本进行加密,解密的原理则反之,下面为源代码:

public class Mainpanel {
	Panel panel, p2;
	Button scan, encrypt, decrypt;
	TextField text;
	TextArea textarea;
	String path;
//	String path="D:\\";
	String FileName;
	Conversion con = new Conversion();
	Charset charset = Charset.forName("GBK");
	BufferedReader encryptRead = null, decryptRead = null;
	FileWriter encryptWrite = null, decryptWrite = null;
/**
 * 面板各属性的设置
 */
	public Mainpanel() {  
		Frame f = new Frame("文件加密");
		f.setLayout(new BorderLayout());
		f.setBounds(550, 300, 400, 350);
		f.setBackground(new Color(245, 222, 179));
		panel = new Panel();
		p2 = new Panel();
		Label l1 = new Label("请选择路径");
		scan = new Button("浏览");
		encrypt = new Button("加密");
		decrypt = new Button("解密");
		text = new TextField(30);
		textarea = new TextArea();
		panel.add(l1);
		panel.add(text);
		panel.add(scan);
		f.add(panel, BorderLayout.NORTH);
		p2.add(encrypt);
		p2.add(decrypt);
		f.add(p2, BorderLayout.SOUTH);
		f.add(textarea, BorderLayout.CENTER);
		f.pack();
		f.setVisible(true);
		f.addWindowListener(new WindowClose());
		scan.addActionListener(new Scanner());
		encrypt.addActionListener(new Encrypter());
		decrypt.addActionListener(new Decrypter());
	}

	class WindowClose extends WindowAdapter { // 关闭窗口的监听事件
		public void windowClosing(WindowEvent e) {
			System.exit(0);
		}
	}
/**
 * 浏览按钮的监听事件
 * {@link Scanner}
 *
 */
	class Scanner implements ActionListener { 
		public void actionPerformed(ActionEvent e) {
			JFileChooser file = new JFileChooser(".");
//			JFileChooser file = new JFileChooser(path);
			int result = file.showOpenDialog(null);
			if (result == JFileChooser.APPROVE_OPTION) {
				FileName = file.getSelectedFile().getName(); // 返回选中的文件及其文件名
				path = file.getSelectedFile().getAbsolutePath(); // getSelectedFile()返回选中的文件。;返回此抽象路径名的绝对路径名字符串。
				text.setText(path); // 将此文本组件显示的文本设置为指定文本。
				BufferedReader reader = null;
				try {
					File file1 = new File(path);
					FileReader fr = new FileReader(file1);
					reader = new BufferedReader(fr);
					String tc;
					textarea.setText("");
					while ((tc = reader.readLine()) != null) {
						byte[] m = tc.getBytes(); // getBytes()使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
						String M = new String(m, 0, m.length, charset);
						textarea.append(M);
					}
					reader.close();
				} catch (Exception e1) {
					textarea.append("文件读取出错!");
				}
			}
		}
	}

/**
 * 
 * 加密按钮的监听事件
 *
 */
	class Encrypter implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			try {
				String a = text.getText(); // 返回此文本组件表示的文本。
				File Exist = new File("加密" + FileName);
				if (a.equals(""))
					throw new MyException1("请选择路径!");
				if (Exist.exists())
					throw new MyException1("已存在加密文件,请先删除,再进行加密!");
				try {
					textarea.setText("");
					File file1 = new File(path);
					FileReader fr = new FileReader(file1);
					encryptRead = new BufferedReader(fr);
					encryptWrite = new FileWriter("加密" + FileName, true);
					String i;
					while ((i = encryptRead.readLine()) != null) {
						byte[] m = i.getBytes();
						String M = Conversion.parseByte2HexStr(m);
						encryptWrite.write(M);
						textarea.append(M);
					}
					encryptWrite.close();
					JOptionPane.showMessageDialog(null, "加密成功", "祝贺您", JOptionPane.PLAIN_MESSAGE);
				} catch (IOException e1) {
				}
			} catch (MyException1 e2) {
			}
		}
	}
/**
 * 
 * 解密按钮的监听事件
 *
 */
	class Decrypter implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			try {
				String a = text.getText();
				File Exist = new File("解密" + FileName);
				if (a.equals(""))
					throw new MyException1("请选择路径!");
				if (Exist.exists())
					throw new MyException1("已存在解密文件,请先删除!");
				try {
					textarea.setText("");
					File file1 = new File(path);
					FileReader fr = new FileReader(file1);
					decryptRead = new BufferedReader(fr);
					decryptWrite = new FileWriter("解密" + FileName, true);
					String i;
					while ((i = decryptRead.readLine()) != null) {
						byte[] m = Conversion.parseHexStr2Byte(i);
						String M = new String(m, 0, m.length, charset);
						decryptWrite.write(String.valueOf(M));
						textarea.append(M); // 将给定文本追加到文本区的当前文本。
					}
					decryptWrite.close();
					JOptionPane.showMessageDialog(null, "解密成功", "祝贺您", JOptionPane.PLAIN_MESSAGE);
				} catch (IOException e1) {
				}
			} catch (MyException1 e2) {
			}
		}
	}

	class MyException1 extends Exception {
		private static final long serialVersionUID = 1L;

		public MyException1(String message) {
			JOptionPane.showMessageDialog(null, message);
		}
	}
	}

/**
 *  主函数入口
 * @param args
 */
	public static void main(String[] args) {
		new Mainpanle(); // 主函数入口
	}

以下为二进制与十六进制互转的代码:

public class conversion {
	/**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
	  /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;}
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
}

代码只有经常性的敲写,才能记住代码规律,熟悉代码间的语法语义,了解各大类中的各种功能的方法。首篇文章,请多关照!
——这是一条不归路……

    原文作者:Doctor_96
    原文地址: https://blog.csdn.net/weixin_42350858/article/details/83279167
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。