留着参考

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. C#获取CPU编号

    //System.Management;//需要添加引用(系统自带) /// <summary> /// 获取cpu编号 /// </summary> /// <retu ...

  2. Python 实现购物商城,含有用户入口和商家入口

    这是模拟淘宝的一个简易的购物商城程序. 用户入口具有以下功能: 登录认证 可以锁定用户 密码输入次数大于3次,锁定用户名 连续三次输错用户名退出程序 可以选择直接购买,也可以选择加入购物车 用户使用支 ...

  3. python3----生成器generator(yield)

    # 列表推导式a = [i for i in range(100) if not(i % 2) and (i % 3)]print(a)# 字典推导式b = {i: i % 2 == 0 for i ...

  4. Innodb间隙锁,细节讲解(转)

    关于innodb间隙锁,网上有很多资料,在此不做赘述,我们讲解一下关于innodb的间隙锁什么情况下会产生的问题. 网上有些资料说innodb的间隙锁是为了防止幻读,这个论点真的是误人子弟.了解inn ...

  5. 自动更新本地 GIT 仓库

    随着开源软件的兴起,尤其是 GITHUB 的蓬勃发展,很多开源软件都通过 GIT 进行管理,在我的计算机上就一个目录是我关注并使用的开源软件 GIT 本地副本,如何定期更新这些仓库,一个个的更新太累人 ...

  6. Mac中pico编辑器的使用方法

    Pico是一个由华盛顿大学(University of Washington)计算与通讯研究所(Computing and Communications Group)编写并维护的文本编辑程序,在多个版 ...

  7. css3动画效果:1基础

    css动画分两种:过渡效果transition .关键帧动画keyframes 一.过渡效果transition 需触发一个事件(如hover.click)时,才改变其css属性. 过渡效果通常在用户 ...

  8. pip install selenium==版本号 报错

    安装selenium是注意不要带版本号直接用如下命令: pip install selenium

  9. Zend Studio 中创建简单的phpfile模板和xhtml类phpfile模板

    <!--简单的phpfile模板,带有创建时间和作者--><?php/*** ==============================================* @dat ...

  10. Javascript调用WinForm方法

    window.external.MyMessageBox('javascript访问C#代码')