留着参考

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. 进程间通信之WM_COPYDATA方式反思,回顾和总结

    许多Windows程序开发者喜欢使用WM_COPYDATA来实现一些进程间的简单通信(笔者也正在学习共享内存的一些知识来实现一些更高级的通信),这篇文章描述了笔者在使用这项技术时候的一些总结以及所遇到 ...

  2. 8、手把手教React Native实战之ReactJS组件生命周期

    1.创建阶段 getDefaultProps:处理props的默认值 在React.createClass调用 2.实例化阶段 React.render(<HelloMessage 启动之后 g ...

  3. [转]C# 获取指定目录下所有文件信息、移动目录、拷贝目录

    原文:http://blog.csdn.net/vchao13/article/details/6200255 1.获取指定目录下所有文件信息 /// <summary> /// 返回指定 ...

  4. thrift框架总结,可伸缩的跨语言服务开发框架

    thrift框架总结,可伸缩的跨语言服务开发框架 前言: 目前流行的服务调用方式有很多种,例如基于 SOAP 消息格式的 Web Service,基于 JSON 消息格式的 RESTful 服务等.其 ...

  5. SVN上新增一个项目和用户

    author:headsen chen date:2018-05-04  11:01:08  1,在SVN服务器上,打开SVN的软件,在项目里新建一个文件夹.在Repositories下面 2,use ...

  6. 【Charles】使用教程+破解+Windows版本https乱码+https证书安装注意

    一.使用教程参考: 这一篇就够了,其他都是大同小异.Windows版和MAC版使用没太多区别. Charles 从入门到精通 | 唐巧的博客 https://blog.devtang.com/2015 ...

  7. 制作简易app个人总结

    1.每次修改app.js或者其他路由js文件,都必须重启node app.js,否则修改不起作用!!! 2.<link rel="stylesheet" href=" ...

  8. T420 开启麦克风

    买来之后一直没注意过麦克风的问题,今天基友们群视频,才发现我的机器是哑的 打开录音设备,发现没有设备 重装驱动无果 打开BIOS,在安全选项——IO/Access中将Microphone 设为 Ena ...

  9. 如何查看python的api

    如何查看python selenium的api   经常发现很多同学装好了python+selenium webdriver开发环境后不知道怎么去查看api文档,在这里乙醇简单介绍一下具体方法,其实非 ...

  10. Qt隐式共享与显式共享

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/Amnes1a/article/details/69945878Qt中的很多C++类都使用了隐式数据共 ...