【Java】Swing+IO流实现一个简单的文件加密程序(较完整版)
留着参考
beans
package com.my.bean; import java.io.Serializable; public class EncryptedFile implements Serializable { private String filePath; private String keyFullName; public EncryptedFile() { } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public String getKeyFullName() { return keyFullName; } public void setKeyFullName(String keyFullName) { this.keyFullName = keyFullName; } @Override public String toString() { return "EncryptedFile{" + "filePath='" + filePath + '\'' + ", keyFullName='" + keyFullName + '\'' + '}'; } }
package com.my.bean; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class User implements Serializable { private String username; private String password; private List<EncryptedFile> encryptedFileList = new ArrayList<>(); public User() { } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public List<EncryptedFile> getEncryptedFileList() { return encryptedFileList; } public void setEncryptedFileList(List<EncryptedFile> encryptedFileList) { this.encryptedFileList = encryptedFileList; } }
service
package com.my.service; import com.my.bean.User; import java.io.*; public class EncryptService { private String username; private static String DEFAULT_KEY_URL = ".//user//"; private int key[] = new int[128]; public EncryptService(User user) { username = user.getUsername(); } public void readKey(String keyFullName) { File keyFile = new File(DEFAULT_KEY_URL + username + "//" + keyFullName); FileInputStream localKey = null; try { localKey = new FileInputStream(keyFile); for (int i = 0; i < 128; ++i) { key[i] = localKey.read(); } } catch (Exception e) { e.printStackTrace(); } finally { if (localKey != null) { try { localKey.close(); } catch (IOException e) { e.printStackTrace(); } } } } public void makeKey(String keyName) { FileOutputStream fos = null; try { File keyFile = new File(DEFAULT_KEY_URL + username + "//" + keyName + ".key"); fos = new FileOutputStream(keyFile); for (int i = 0; i < 128; ++i) { fos.write((int) (Math.random() * 128)); } readKey(keyName + ".key"); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } public void encryptFile(String filePath, String keyFullName) { readKey(keyFullName); FileInputStream in = null; FileOutputStream out = null; File inFile = new File(filePath); File outFile = new File(inFile.getParent() + "//TEMP_FILE"); try { in = new FileInputStream(inFile); out = new FileOutputStream(outFile); int length = in.available(); for (int i = 0; i < length; ++i) { out.write(in.read() + key[i % 128]); } } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } inFile.delete(); outFile.renameTo(inFile); } public void decryptFile(String filePath, String keyFullName) { readKey(keyFullName); FileInputStream in = null; FileOutputStream out = null; File inFile = new File(filePath); File outFile = new File(inFile.getParent() + "//TEMP_FILE"); try { in = new FileInputStream(inFile); out = new FileOutputStream(outFile); int length = in.available(); for (int i = 0; i < length; ++i) { out.write(in.read() - key[i % 128]); } } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } inFile.delete(); outFile.renameTo(inFile); } } class EncryptServiceTest { public static void main(String[] args) { // 在完整程序中用户信息由Main界面提供 User user = new User(); user.setUsername("xkfx"); EncryptService encryptService = new EncryptService(user); encryptService.encryptFile(".//hi.txt", "main.key"); encryptService.decryptFile(".//hi.txt", "main.key"); } }
package com.my.service; import com.my.bean.EncryptedFile; import com.my.bean.User; import java.io.*; import java.util.List; public class PersistenceService { private static String DEFAULT_DATA_URL = ".//conf//"; String username; public PersistenceService(String username) { this.username = username; } public void loadData(User user) { BufferedReader br; try { br = new BufferedReader(new FileReader(new File(DEFAULT_DATA_URL + username + ".user"))); while (br.ready()) { EncryptedFile file = new EncryptedFile(); file.setFilePath(br.readLine()); file.setKeyFullName(br.readLine()); user.getEncryptedFileList().add(file); } } catch (Exception e) { e.printStackTrace(); } } public void saveData(User user) { PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter(new File(DEFAULT_DATA_URL + username + ".user"))); for (EncryptedFile file : user.getEncryptedFileList()) { pw.println(file.getFilePath()); pw.println(file.getKeyFullName()); } } catch (Exception e) { e.printStackTrace(); } finally { try { pw.close(); } catch (Exception e) { e.printStackTrace(); } } } } class PersistenceServiceTest { public static void main(String[] args) { User user = new User(); user.setUsername("zzz"); EncryptedFile file1 = new EncryptedFile(); file1.setFilePath("aaaa"); file1.setKeyFullName("bbbbbbbbbb"); EncryptedFile file2 = new EncryptedFile(); file2.setFilePath("xxxx"); file2.setKeyFullName("qqqqqqq"); user.getEncryptedFileList().add(file1); user.getEncryptedFileList().add(file2); PersistenceService persistenceService = new PersistenceService(user.getUsername()); // 存进文件,默认为 conf/username.user persistenceService.saveData(user); // 取出来并输出 persistenceService.loadData(user); for (EncryptedFile file : user.getEncryptedFileList()) { System.out.println(file); } } }
UI
package com.my.ui; import com.my.bean.EncryptedFile; import com.my.bean.User; import javax.swing.*; import java.awt.*; public class EncryptedFileManagement extends JFrame { private User user; private Main mainFrame; public EncryptedFileManagement(User user) { this.user = user; setTitle("加密文件管理"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setLocationRelativeTo(null); setResizable(false); setLayout(new BorderLayout()); updateFrame(); } public void setMainFrame(Main mainFrame) { this.mainFrame = mainFrame; // 传递主界面的一个引用,以便监控子窗口的Action } public void addEncryptedFile(String filePath, String keyFullName) { EncryptedFile encryptedFile = new EncryptedFile(); user.getEncryptedFileList().add(encryptedFile); encryptedFile.setFilePath(filePath); encryptedFile.setKeyFullName(keyFullName); updateFrame(); } public boolean removeEncryptedFile(String filePath, String keyFullName) { int listSize = user.getEncryptedFileList().size(); for (int i = 0; i != listSize; ++i) { EncryptedFile file = user.getEncryptedFileList().get(i); if (file.getFilePath().equals(filePath) && file.getKeyFullName().equals(keyFullName)) { user.getEncryptedFileList().remove(i); updateFrame(); return true; } } return false; } JPanel listPanel = new JPanel(); public void updateFrame() { listPanel.removeAll(); // 必须调用这个方法,否则视图显示将和真实情况不匹配 listPanel.setLayout(new GridLayout(user.getEncryptedFileList().size(), 2)); for (EncryptedFile file : user.getEncryptedFileList()) { JButton buttonFilePath = new JButton("■" + file.getFilePath()); JButton buttonKeyFullPath = new JButton("▲" + file.getKeyFullName()); listPanel.add(buttonFilePath); listPanel.add(buttonKeyFullPath); // 注册事件监听 buttonFilePath.addActionListener(mainFrame); buttonKeyFullPath.addActionListener(mainFrame); buttonFilePath.setFocusPainted(false); buttonKeyFullPath.setFocusPainted(false); }; setSize(482, user.getEncryptedFileList().size()*44 + 57); add(listPanel, BorderLayout.CENTER); } } class EncryptedFileManagementTest { public static void main(String[] args) { // 实际中是代理Main中的User User user = new User(); user.setUsername("xkfx"); EncryptedFileManagement frame = new EncryptedFileManagement(user); Main main = new Main(user); main.setVisible(true); frame.setMainFrame(main); for (int i = 0; i != 5; ++i) { frame.addEncryptedFile("D:\\workspace\\untitled1\\hi.txt", i + "main.key"); } frame.setVisible(true); } }
package com.my.ui; import com.my.bean.User; import com.my.service.EncryptService; import com.my.service.PersistenceService; import com.my.util.Iconst; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; public class Main extends JFrame implements ActionListener { // 保存服务对象 private User user; private EncryptService encryptService; PersistenceService persistenceService; private EncryptedFileManagement encryptedFileManagement; // 窗体默认大小 private static final int DEFAULT_WIDTH = 416; private static final int DEFAULT_HEIGHT = 145; // 全局组件 private JFileChooser fileChooser; private JButton buttonEncrypt; private JButton buttonDecrypt; private JButton buttonMakeNewKey; private JButton buttonEncryptedFileManagement; private JButton buttonExit; private JTextField textFilePath; private JTextField textKeyName; // 保存当前文件、密匙路径 private String filePath; private String keyPath; public void setFilePath(String filePath) { this.filePath = filePath; } public void setKeyPath(String keyPath) { this.keyPath = keyPath; } // 窗体初始化 public Main(User user) { // 初始化用户和服务 this.user = user; encryptService = new EncryptService(this.user); persistenceService = new PersistenceService(this.user.getUsername()); persistenceService.loadData(this.user); encryptedFileManagement = new EncryptedFileManagement(this.user); encryptedFileManagement.setMainFrame(this); // 初始化界面 setTitle("用户ID:" + user.getUsername()); setDefaultCloseOperation(0); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); setResizable(false); setLocationRelativeTo(null); JPanel bigPanel = new JPanel(); // 布置主要界面 textFilePath = new JTextField(); textKeyName = new JTextField(); JButton buttonChooseFile = new JButton(Iconst.CHOOSE_FILE); JButton buttonChooseKey = new JButton(Iconst.CHOOSE_KEY); textFilePath.setEditable(false); textKeyName.setEditable(false); buttonChooseKey.setFocusPainted(false); buttonChooseFile.setFocusPainted(false); bigPanel.setLayout(new GridLayout(2, 3)); bigPanel.add(new JLabel("文件路径")); bigPanel.add(textFilePath); bigPanel.add(buttonChooseFile); bigPanel.add(new JLabel("密匙名称")); bigPanel.add(textKeyName); bigPanel.add(buttonChooseKey); JPanel buttonPanel = new JPanel(); // 布置按钮界面 buttonEncrypt = new JButton(Iconst.ENCRYPT); buttonDecrypt = new JButton(Iconst.DECRYPT); buttonMakeNewKey = new JButton(Iconst.CREATE_NEW_KEY); buttonEncryptedFileManagement = new JButton(Iconst.ENCRYPTED_FILE_MANAGEMENT); buttonExit = new JButton(Iconst.EXIT); buttonEncrypt.setFocusPainted(false); buttonDecrypt.setFocusPainted(false); buttonMakeNewKey.setFocusPainted(false); buttonEncryptedFileManagement.setFocusPainted(false); buttonExit.setFocusPainted(false); buttonPanel.setLayout(new FlowLayout()); buttonPanel.add(buttonEncrypt); buttonPanel.add(buttonDecrypt); buttonPanel.add(buttonMakeNewKey); buttonPanel.add(buttonEncryptedFileManagement); buttonPanel.add(buttonExit); // 布置窗体 setLayout(new BorderLayout()); add(bigPanel, BorderLayout.CENTER); add(buttonPanel, BorderLayout.SOUTH); // 注册事件监听 buttonChooseFile.addActionListener(this); buttonChooseKey.addActionListener(this); buttonMakeNewKey.addActionListener(this); buttonEncrypt.addActionListener(this); buttonDecrypt.addActionListener(this); buttonEncryptedFileManagement.addActionListener(this); buttonExit.addActionListener(this); // 创建文件选择器 fileChooser = new JFileChooser(); } @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().charAt(0) == "■".charAt(0)) { String filePath = e.getActionCommand().substring(1, e.getActionCommand().length()); setFilePath(filePath); textFilePath.setText(filePath); } if (e.getActionCommand().charAt(0) == "▲".charAt(0)) { String keyFullName = e.getActionCommand().substring(1, e.getActionCommand().length()); setKeyPath(".//user//" + user.getUsername() + "//" + keyFullName); textKeyName.setText(keyFullName); } if (e.getActionCommand().equals(Iconst.CHOOSE_FILE)) { fileChooser.setCurrentDirectory(new File(".")); int result = fileChooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { filePath = fileChooser.getSelectedFile().getPath(); textFilePath.setText(filePath); } } if (e.getActionCommand().equals(Iconst.CHOOSE_KEY)) { fileChooser.setCurrentDirectory(new File(".//user//" + user.getUsername())); int result = fileChooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { keyPath = fileChooser.getSelectedFile().getPath(); textKeyName.setText(new File(keyPath).getName()); } } if (e.getActionCommand().equals(Iconst.ENCRYPT)) { if (filePath != null && !"".equals(filePath) && textKeyName.getText() != null && !"".equals(textKeyName.getText())) { encryptService.encryptFile(filePath, textKeyName.getText()); encryptedFileManagement.addEncryptedFile(filePath, textKeyName.getText()); JOptionPane.showMessageDialog(this, "加密成功"); } else { JOptionPane.showMessageDialog(this, "文件路径、密匙名称不能为空!"); } } if (e.getActionCommand().equals(Iconst.DECRYPT)) { if (filePath != null && !"".equals(filePath) && textKeyName.getText() != null && !"".equals(textKeyName.getText()) ) { if (encryptedFileManagement.removeEncryptedFile(filePath, textKeyName.getText())) { encryptService.decryptFile(filePath, textKeyName.getText()); JOptionPane.showMessageDialog(this, "还原成功"); } else { JOptionPane.showMessageDialog(this, "该文件未被加密或密匙不匹配"); } } else { JOptionPane.showMessageDialog(this, "文件路径、密匙名称不能为空!"); } } if (e.getActionCommand().equals(Iconst.CREATE_NEW_KEY)) { String keyName = JOptionPane.showInputDialog(this, "请输入新密匙的名称:"); if (keyName != null && !"".equals(keyName)) { encryptService.makeKey(keyName); JOptionPane.showMessageDialog(this, "成功创建新的密匙"); } // 更新当前密匙路径 setKeyPath(".//user//" + user.getUsername() + "//" + keyName + ".key"); textKeyName.setText(keyName + ".key"); } if (e.getActionCommand().equals(Iconst.ENCRYPTED_FILE_MANAGEMENT)) { if (user.getEncryptedFileList().size() == 0) { JOptionPane.showMessageDialog(this, "加密文件为空"); } else { encryptedFileManagement.setVisible(true); } } if (e.getActionCommand().equals(Iconst.EXIT)) { if (JOptionPane.showConfirmDialog(this,"确定退出?") == 0) { persistenceService.saveData(user); this.dispose(); System.exit(0); } } } } class MainTest { public static void main(String[] args) { User user = new User(); user.setUsername("xkfx"); EventQueue.invokeLater(() -> { JFrame frame = new Main(user); frame.setVisible(true); }); } }
工具类
package com.my.util; /** * 常量定义 */ public interface Iconst { public static final String LOGIN = "登陆"; public static final String REGISTER = "注册"; public static final String CHOOSE_FILE = "选择文件"; public static final String CHOOSE_KEY = "选择密匙"; public static final String ENCRYPT = "加密"; public static final String DECRYPT = "还原"; public static final String CREATE_NEW_KEY = "生成新的密匙"; public static final String ENCRYPTED_FILE_MANAGEMENT = "管理文件"; public static final String EXIT = "退出"; }
由于电脑原因,源代码的编码可能会有一些问题:http://pan.baidu.com/s/1o8hsWd0