留着参考

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

【Java】Swing+IO流实现一个简单的文件加密程序(较完整版)的更多相关文章

  1. 【Java】Swing+IO流实现一个简单的文件加密程序(demo版)

    留着参考 EncrytService package com.my.service; import java.io.File; import java.io.FileInputStream; impo ...

  2. Java基础-IO流对象之随机访问文件(RandomAccessFile)

    Java基础-IO流对象之随机访问文件(RandomAccessFile) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.RandomAccessFile简介 此类的实例支持对 ...

  3. 使用IO流实现一个简单的小Dome

    (一) 在电脑D盘下创建一个文件为HelloWorld.txt文件,判断他是文件还是目录,在创建一个目录IOTest,之后将HelloWorld.txt移动到IOTest目录下去:之后遍历IOTest ...

  4. 【Java】IO流简单分辨

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/5827509.html Java的IO流体系十分庞大,并且体系层次稍复杂,很容易记混或记错.在此,我把平时经常用 ...

  5. Java基础——IO流

    今天刚刚看完java的io流操作,把主要的脉络看了一遍,不能保证以后使用时都能得心应手,但是最起码用到时知道有这么一个功能可以实现,下面对学习进行一下简单的总结: IO流主要用于硬板.内存.键盘等处理 ...

  6. Java之IO流详解

    IO流 Input/Output 完成输入/输出 应用程序运行时——数据在内存中  ←→ 把数据写入硬盘(磁带)  内存中的数据不可持久保存的  输入:从外部存储器(硬盘.磁带.U盘)把数据读入内存. ...

  7. JAVA中IO流总结

    本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/42119261 我想你对JAVA的IO流有所了解,平时使用的 ...

  8. Java的IO流——(七)

    目录结构:

  9. Java基础-IO流对象之压缩流(ZipOutputStream)与解压缩流(ZipInputStream)

    Java基础-IO流对象之压缩流(ZipOutputStream)与解压缩流(ZipInputStream) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 之前我已经分享过很多的J ...

随机推荐

  1. html 复选框(checkbox)和单选框(radio)与文字水平垂直居中对齐

    对 input与label同时设置CSS input,label{ vertical-align:middle; }

  2. 如何让VS检查函数和类Comment的添加情况

    问题: 现在有一个大的项目,我不能确定是否每个类和函数是否已经加上了comments,是否每个comments都是标注正确的. VS中有没有检查Comments的功能? 解决方案: 1.右击proje ...

  3. Less-css扩展多样式

    //扩展Extend Use Method:以在study上扩展多个的样式为例 //Share style 1 .style1{ width:200px; height:15px; color:#ff ...

  4. 01Go开发环境搭建(参考无闻大神)

    一直安装下一步就可以了 GOPATH是工作目录 GOROOT是安装目录 如果有多个工作目录,就需要我们用分号进行分隔

  5. info 手册

      info flex 可以查看flex帮助. h就可以看到相关命令,常用命令已经加粗: x           关闭此帮助窗口. q           一并退出 Info. RET         ...

  6. 每隔10秒钟打印一个“Helloworld”

    /** * 每隔10秒钟打印一个“Helloworld” */ public class Test03 { public static void main(String[] args) throws ...

  7. IIS设置文件 Robots.txt 禁止爬虫

    robots.txt用于禁止网络爬虫访问网站指定目录.robots.txt的格式采用面向行的语法:空行.注释行(以#打头).规则行.规则行的格式为:Field: value.常见的规则行:User-A ...

  8. [NOIP2018TG]保卫王国

    [NOIP2018TG]保卫王国 BZOJ luogu 当动态dp模板题写的,(全集-最大点权独立集)不能放军队的+inf,必须放军队-inf即可 注意矩阵乘法的顺序问题 #define ll lon ...

  9. python setup.py install 报错:error: [WinError 3] 系统找不到指定的路径。: 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\PlatformSDK\\lib

    Outline 在通过 setup.py 安装python模块时,遇到了以下报错: # 执行 python setup.py install # 报错: error: [WinError 3] 系统找 ...

  10. 基本数据类型补充、set集合、深浅拷贝

    一.基本数据类型补充 1,关于int和str在之前的学习中已经介绍了80%以上了,现在再补充一个字符串的基本操作 str.join(可迭代对象): li = ['李嘉诚','何炅','海峰','刘嘉玲 ...