【Java】Swing+IO流實現一個簡單的文件加密程序(較完整版)
阿新 • • 發佈:2017-07-05
move 初始 baidu images 文件選擇器 while login 一個 ktr
留著參考
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 implementsSerializable { 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
【Java】Swing+IO流實現一個簡單的文件加密程序(較完整版)