【密码学】Java课设-文件加密系统(适用于任何文件)

简介: 【密码学】Java课设-文件加密系统(适用于任何文件)

Java实现文件加密解密


前言

一、密码学入门

1.对称加密

2.非对称加密

二、程序代码

1.welcome类(欢迎界面)

2.Log类(登录界面)

3.Register类(注册界面)

4.Index类(首页界面)

5.MajorFR类(加/解密文件操作界面)

6.FileAction类(加密算法)

7.Me类(九芒星的博客)


前言


文档显示乱码相信大家一定不陌生,一份很喜欢的文档内容/数据,下载到自己电脑上却是这样的

项目中一些核心程序打开是这样的

文件加密,不仅可以提高数据安全性,还可以在很大程度上保护个人权益/财产不被侵犯。

本篇文章采用的是对称加密方式,效果如下。

一、密码学入门


常见的加密方式分为两种,对称加密和非对称加密。


1.对称加密


对称加密简单来说就是两个相同的钥匙开同一把锁。


它符合大多数人的思维逻辑,就好比你们家钥匙可以在门内外实现上锁开锁操作。缺点就是解密是加密的逆过程,知道加密规则立马可以获得解密规则,安全性较低。


对称加密最早使用是在公元前54年,古罗马军事统帅凯撒大帝发明的凯撒密码,在战争中把写在长布条上的情报系在信使的腰上进行传递。

只有将该布条缠在特定粗细的木棒中,横向观看才能看到传递的真正信息,单截获一个布条很难获取到上面的信息。

在信息传递落后的时代中由于凯撒密码的使用,使得凯撒大帝在战争中占据了先发优势,并赢得了多次胜利。

但是由于凯撒加密规则过于简单,它仅采用位移加密方式,只对26个字母进行位移替换加密,破译相对简单,最多尝试25次即可破解内容。

即便如此,在一战和二战中对称加密仍然应用非常广泛,编译员使用英文字母,阿拉伯数字,符号进行对称加密。但加密原理不变,破译只需花费更多时间。

这也就解释了为什么在谍战片中总能看到一群人在不停的计算所有的可能性,利用归纳出的各字符频率来还原密钥

2.非对称加密


非对称加密简单来说就是两个不同的钥匙开同一把锁

非对称加密分为公钥和私钥,接发双方各有一个私钥,公钥公开运输。甲将消息“我爱你”利用公钥加密,并附属私钥A加密过的签名运输到乙,乙接到消息用私钥B解密并确认签名正确后则成功接收。

总结:

1.发送者只需要知道加密密钥;

2.接收者只需要知道解密密钥

3.解密密钥不可以被窃听者获取

4.加密密钥被窃听者获取也不影响信息安全

通俗来说,对于对称加密方式,直接用密钥传输,破译者更易抢夺密钥,通过暴力破解来获取信息;

而对于非对称加密方式,破译者不易抢夺私钥,并且获取单向私钥无法解开密文,通常采用截取公钥并替换内容,伪装成发送方对接收方进行信息篡改和窃取来达到己方利益。


因此,对于公钥信息的可靠性问题,研究人员提出了私钥数字签名的方式来解决信息传递安全。下图显示的文件就是数字签名的实例。

生活中最典型的例子就是,淘宝买家和卖家依靠阿里巴巴中间过渡来进行可靠交流。


二、程序代码


1.welcome类(欢迎界面)


设计很简单,一张背景图片,中间添加进入系统按钮,实现如下:

package 九芒星加密;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class welcome extends JFrame{
  //创建一个容器
  Container ct;
  //创建背景面板
  BackgroundPanel bgp;  
  public static void main(String[] args){
     new welcome();
  }
  public welcome(){
    ct=this.getContentPane();
    this.setLayout(null);
    setTitle("九芒星_文件加密/解密工具");
    bgp=new BackgroundPanel((new ImageIcon("src/image/welcome.jpg")).getImage());
    bgp.setBounds(0,0,600,400);
    ct.add(bgp);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
    JLabel show=new JLabel("欢迎进入九芒星加密系统");
    JButton in=new JButton("点击进入"); 
    in.setFont(new Font("黑体",Font.BOLD,25));
    show.setBounds(250,20,500,50);//组件位置
    show.setFont(new Font("黑体",Font.BOLD,30));
    Container mk=getContentPane();//获取一个容器
    in.setBounds(230,200,150,50);
    setBounds(660,340,600,400);
    mk.add(show);
    mk.add(in);
    setVisible(true);//使窗体可视化
    mk.setLayout(null);
    in.addActionListener(new ActionListener(){//对注册按钮添加监听事件
      @SuppressWarnings("deprecation")
      @Override
      public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub
        new Log();
      }
    });
  }
}
  class BackgroundPanel extends JPanel{
    Image im;
    public BackgroundPanel(Image im){
       this.im=im;
       this.setOpaque(true);
    }
    //Draw the back ground.
    public void paintComponent(Graphics g){
       super.paintComponents(g);
       g.drawImage(im,0,0,this.getWidth(),this.getHeight(),this);
    }
  }

2.Log类(登录界面)


添加几个面板,按钮,条件判断用户名和密码正确性(没有连数据库,感兴趣可以自己链接)


注:密码采用密文输入

package 九芒星加密;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Log extends JFrame {
  public Log() { 
    setSize(600,400);//设计窗体的大小
    this.getContentPane().setBackground(Color.CYAN);//设置窗口背景颜色
    JLabel title=new JLabel("登录界面");
    JLabel root=new JLabel("用户名"); //实例化JLabel对象    
    JLabel ps=new JLabel("密码"); 
    JTextField rootTXT=new JTextField(15);//实例化用户名文本框   
    JPasswordField psTXT=new JPasswordField(15);//实例化密码框    
    psTXT.setEchoChar('*');//将输入密码框中的密码以*显示出来
    JButton log=new JButton("登录");    
    JButton register=new JButton("注册");   
    title.setBounds(250,20,500,50);//组件位置
    title.setFont(new Font("黑体",Font.BOLD,30));
    root.setBounds(100,100,500,50);//组件位置
    root.setFont(new Font("黑体",Font.BOLD,30));
    ps.setBounds(100,170,500,50);//组件位置
    ps.setFont(new Font("黑体",Font.BOLD,30));
    log.setFont(new Font("黑体",Font.BOLD,25));
    register.setFont(new Font("黑体",Font.BOLD,25));
    setTitle("九芒星_文件加密/解密工具");
    setVisible(true);//使窗体可视化
    Container mk=getContentPane();//获取一个容器
    mk.add(title);
    mk.add(root);
    mk.add(ps);
    mk.add(rootTXT);
    mk.add(psTXT);
    mk.add(log);
    mk.add(register);
    setBounds(660,340,600,400);
    mk.setLayout(null);
    rootTXT.setBounds(200,100,300,40);
    psTXT.setBounds(200,170,300,40);
    log.setBounds(180,260,100,50);
    register.setBounds(360,260,100,50);
    log.addActionListener(new ActionListener() {//对确定按钮添加监听事件
      @SuppressWarnings("deprecation")
      @Override
      public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub
        if(rootTXT.getText().trim().equals("root")&&new String(psTXT.getPassword()).equals("123456")) {//equals函数进行用户名和密码的匹配
          JOptionPane.showMessageDialog(null,"登录成功,即将进入文件加密系统");
          new Index("九芒星_文件加密/解密工具");
        }else if(!rootTXT.getText().trim().equals("root")) {
          JOptionPane.showMessageDialog(null, "请输入正确的用户名!");
        }else if(new String(psTXT.getPassword()).length() < 6||new String(psTXT.getPassword()).length() > 6) {
          JOptionPane.showMessageDialog(null, "请输入6位密码!");
        }
        else {
          JOptionPane.showMessageDialog(null, "登录失败,请确认用户名和密码无误");
        }
      }
    });
    register.addActionListener(new ActionListener(){//对注册按钮添加监听事件
      @SuppressWarnings("deprecation")
      @Override
      public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub
        new Register();       
      }     
    });   
  }
    public static void main(String[] args) {
      new Log();
    }   
  }

3.Register类(注册界面)


和登录界面类似,由于注册需要数据库支持,我就简单写了一个图形化界面。

是个空架子,各位有兴趣自己发挥!

package 九芒星加密;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Register extends JFrame {
  public Register() {
    setSize(600,400);//设计窗体的大小
    setTitle("九芒星_文件加密/解密工具");
        //设置背景图
        ImageIcon backbround = new ImageIcon("./me1.jpg");
        //将背景图进行压缩,一般如果你想显示一整张图片,就得把大小设置跟窗口一样
    Image image = backbround.getImage(); 
    Image smallImage = image.getScaledInstance(500, 500, Image.SCALE_FAST);
    ImageIcon backbrounds = new ImageIcon(smallImage);
    //将图片添加到JLable标签 
    JLabel jlabel = new JLabel(backbrounds);
    //设置标签的大小
    jlabel.setBounds(0,0, getWidth(),getHeight() );
    //将图片添加到窗口
    add(jlabel);
    this.getContentPane().setBackground(Color.PINK);//设置窗口背景颜色
    JLabel root=new JLabel("用户名"); //实例化JLabel对象    
    JLabel ps=new JLabel("密码");
    JLabel again=new JLabel("再次确认");
    JTextField rootTXT=new JTextField(15);//实例化用户名文本框   
    JPasswordField psTXT=new JPasswordField(15);//实例化密码框  
    JPasswordField againTXT=new JPasswordField(15);//实例化文本框 
    psTXT.setEchoChar('*');
    JButton log=new JButton("返回");    
    JButton register=new JButton("注册");
    setVisible(true);
    Container mk=getContentPane();
    mk.add(root);
    mk.add(ps);
    mk.add(again);
    mk.add(rootTXT);
    mk.add(psTXT);
    mk.add(againTXT);
    mk.add(log);
    mk.add(register);
    setBounds(660,340,600,400);
    mk.setLayout(null);
    root.setBounds(70,50,500,50);//组件位置
    root.setFont(new Font("黑体",Font.BOLD,30));
    ps.setBounds(70,120,500,50);//组件位置
    ps.setFont(new Font("黑体",Font.BOLD,30));
    again.setBounds(70,190,500,50);//组件位置
    again.setFont(new Font("黑体",Font.BOLD,30));
    log.setFont(new Font("黑体",Font.BOLD,25));
    log.setBounds(360,260,100,50);
    register.setFont(new Font("黑体",Font.BOLD,25));
    register.setBounds(180,260,100,50);
    rootTXT.setBounds(200,50,300,40);
    psTXT.setBounds(200,120,300,40);
    againTXT.setBounds(200,190,300,40);
    register.addActionListener(new ActionListener(){
      @SuppressWarnings("deprecation")
      @Override
      public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub
        new Log();
      }
    });
    log.addActionListener(new ActionListener(){
      @SuppressWarnings("deprecation")
      @Override
      public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub
        new Log();
      }
    });
  }
}

4.Index类(首页界面)


首页设计,很简单,主要是鼠标事件监听。


首页共有五个按钮。加密,解密负责跳转到对应页面,实现文件加密系统的基本功能;通过找回密码按钮可以直接打开存放文件加密密码本的文件;如遇紧急情况,可点击保护隐私按钮,程序将调用计算机外部exe,实现锁屏防偷窥。

package 九芒星加密;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Index extends JFrame implements ActionListener{
  private static final int WIDTH = 600;
    private static final int HEIGHT = 400;
    private JPanel mainPanel = new JPanel();
    private JButton encryptBtn = new JButton("加密");
    private JButton decryptBtn = new JButton("解密");
    private JButton myself = new JButton("CSDN——九芒星#");
    private JButton fondpw = new JButton("找回密码");
    private JButton closenow = new JButton("保护隐私");
    private JPanel JPme = new JPanel();
    private JPanel JPfondpw = new JPanel();
    private JPanel JPclosenow = new JPanel();
  private JFrame f1;
  public Index(String title){
        super(title);
        this.init();          
    }
    //初始化
    public void init(){
      JPme.add(myself);
      JPfondpw.add(fondpw);
      JPclosenow.add(closenow);
      fondpw.addActionListener(this);
      closenow.addActionListener(this);
      mainPanel.add(JPme);
      mainPanel.add(JPfondpw);
      mainPanel.add(JPclosenow);
        this.setPanelFont();
        this.addElements();
        this.addListener();
        this.setFramePosition();       
    }
  @Override   
  public void actionPerformed(ActionEvent e) {
    //调用外部存放密码文件
    if(e.getSource() == fondpw){
      this.dispose();       
      OpenPasswordFile();   
    }
    //调用外部锁屏exe
    if(e.getSource() == closenow){
      this.dispose();       
      ProtectPrivacy("E:\\kkkkk\\文件加密解密\\src\\image\\Windows密码锁.exe");    
    }
  }
    //设置组件
    public void setPanelFont(){
        int btnWidth = WIDTH/2 - 20;
        int btnHeight = HEIGHT - 80;
        mainPanel.setLayout(null);
        //加密按钮
        encryptBtn.setBackground(Color.YELLOW);
        encryptBtn.setFont(new Font("黑体",Font.BOLD,50));
        encryptBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));//手状光标
        encryptBtn.setBounds(10,10,btnWidth,btnHeight);//组件位置
        //解密按钮
        decryptBtn.setBackground(Color.CYAN);
        decryptBtn.setFont(new Font("黑体",Font.BOLD,50));
        decryptBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        decryptBtn.setBounds(btnWidth+20,10,btnWidth,btnHeight);
        //九芒星#
        myself.setBackground(Color.PINK);       
        myself.setFont(new Font("黑体",Font.BOLD,20));       
        myself.setBounds(145,335,300,25);
        //找回密码
        fondpw.setFont(new Font("黑体",Font.BOLD,20));       
        fondpw.setBackground(Color.ORANGE);
        fondpw.setBounds(10,335,120,25);
        fondpw.setMargin(new Insets(0,0,0,0));
        //保护隐私
        closenow.setBackground(Color.ORANGE);
        closenow.setFont(new Font("黑体",Font.BOLD,20));       
        closenow.setBounds(460,335,120,25);
    }
    //添加元素
    public void addElements(){
        mainPanel.add(encryptBtn);
        mainPanel.add(decryptBtn);
        mainPanel.add(myself);
        mainPanel.add(fondpw);
        mainPanel.add(closenow);
        this.add(mainPanel);
    }
    //监听
    public void addListener(){  
      //加密
      //鼠标事件监听器
        encryptBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {//鼠标点击
                Index.this.setVisible(false);
                new MajorFR("九芒星_文件加密","加密").init();//加密初始化
            }
            @Override
            public void mouseExited(MouseEvent e) {//鼠标离开(加密组件区域)
                encryptBtn.setFont(new Font("黑体",Font.BOLD,50));
                encryptBtn.setForeground(Color.BLACK);
            }
        });
        //鼠标运动监听器
        encryptBtn.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {//鼠标移动(加密组件区域)
                encryptBtn.setFont(new Font("黑体",Font.BOLD,60));
                encryptBtn.setForeground(Color.RED);//组件区域内保持红色
            }
        });
        //解密
        //鼠标事件监听器
        decryptBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {//鼠标点击
                Index.this.setVisible(false);
                new MajorFR("九芒星_文件解密","解密").init();
            }
            @Override
            public void mouseExited(MouseEvent e) {//鼠标离开
                decryptBtn.setFont(new Font("黑体",Font.BOLD,50));
                decryptBtn.setForeground(Color.BLACK);
            }
        });
        //鼠标运动监听器
        decryptBtn.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {//鼠标移动
                decryptBtn.setFont(new Font("黑体",Font.BOLD,60));
                decryptBtn.setForeground(Color.RED);//组件范围内保持绿色
            }
        });
        myself.addActionListener(new ActionListener(){//对注册按钮添加监听事件
      @SuppressWarnings("deprecation")
      @Override
      public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub
        new Me();
      }
    });
    }
    //打开密码文件
    public  void OpenPasswordFile() {  
    Runtime rn = Runtime.getRuntime();  
    Process p = null;  
    String cmd="rundll32 url.dll FileProtocolHandler file://E:\\kkkkk\\文件加密解密\\src\\image\\otr.txt";
    try {  
      p = rn.exec(cmd);
    } catch (Exception e) {  
      System.out.println("Error exec!");  
    }  
  }
    //调用外部exe,实现密码锁屏
    public static String ProtectPrivacy(String command){
    Runtime runtime = Runtime.getRuntime();
    StringBuilder builder = null;
    try {
      Process process = runtime.exec("cmd /c start " + command);
      BufferedReader brBufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
      String line = "";
      builder = new StringBuilder();
      while ((line = brBufferedReader.readLine()) != null) {
        System.out.println(line);
        builder.append(line);
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return builder.toString();
  }
    //窗口位置
    private void setFramePosition() {
        //获得当前屏幕的长宽
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int screenWidth = (int)screenSize.getWidth();
        int screenHeight = (int)screenSize.getHeight();
        //组件位置
        this.setBounds(screenWidth/2-WIDTH/2,screenHeight/2-HEIGHT/2,WIDTH,HEIGHT);
        /*System.out.println(+screenWidth/2-WIDTH/2);
        System.out.println(+screenHeight/2-HEIGHT/2);
        System.out.println(+WIDTH);
        System.out.println(+HEIGHT);*/
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//窗口关闭
        this.setResizable(false);
        this.setVisible(true);
    }
}

5.MajorFR类(加/解密文件操作界面)


加密解密操作界面,两块比较重要:文件导航和监听事件。

文件导航是用的JFileChooser,它提供了一种文件选择机制,可以打开文件,保存文件,很方便,可以自行查看API。

import javax.swing.JFileChooser()

监听的话相对复杂一些,需要对加密文件的起始地址合法性进行判断,对按钮错误事件的判断提示,对输入密码进行保存等待加密操作等等。

package 九芒星加密;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
public class MajorFR extends JFrame{
  private static final int WIDTH = 600;
    private static final int HEIGHT = 400;
    private String option;
    private JFileChooser fileSelect;
    private JLabel sourceVersion;
    private JTextField sourceText;
    private JButton sourceButton;
    private JLabel aimVersion;
    private JTextField aimText;
    private JButton aimButton;
    private JLabel selectPasswordText;
    private JCheckBox selectPassword;
    private JTextField inPassword;
    private JButton start;
    private JPanel panel1;
    private JPanel panel2;
    private JPanel panel3;
    private JPanel panel4;
    private JFrame f1;
    public MajorFR(String tile,String option){
        super(tile);
        this.option = option;   
    }
    //分页部件初始化
    private void initComponent(){
      //源地址
        fileSelect = new JFileChooser("C:\\");//文件导航窗口
        sourceVersion = new JLabel("请选择待"+option+"的文件/文件夹:");//标签
        sourceText = new JTextField(20);//文本输入
        sourceButton = new JButton("···");//选择按钮
        //目的地址
        aimVersion = new JLabel("请选择"+option+"后文件的存放路径:");//标签
        aimText = new JTextField(20);//文本输入
        aimButton = new JButton("···");//选择按钮
        //选择密码
        if (option.equals("加密")){
            selectPasswordText = new JLabel("使用密码"+option);
        }else if (option.equals("解密")){
            selectPasswordText = new JLabel("该文件有密码");
        }
        if (option.equals("CSDN——九芒星#")){
            System.out.println("点击成功");
        }
        //设置密码
        selectPassword = new JCheckBox();
        inPassword = new JTextField(20);
        //开始加密/解密
        start = new JButton("开始"+this.option);
        start.setEnabled(false);
        //初始化四个面板
        panel1 = new JPanel();
        panel2 = new JPanel();
        panel3 = new JPanel();
        panel4 = new JPanel();
    }
    //初始化
    public void init(){
        this.initComponent();//分页部件
        this.setPanelFont();//首页组件
        this.addElements();//元素
        this.addListener();//监听
        this.setFramePosition();//窗口
    }
    //监听
    private void addListener() {
      //鼠标监听_源地址按钮
        sourceButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {//鼠标点击
                fileSelect.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);//选择文件或者文件夹
                fileSelect.showDialog(panel1, "请选择要"+option+"的文件/文件夹");
                File file = fileSelect.getSelectedFile();
                if(file!=null)
                    sourceText.setText(file.getAbsolutePath());//源地址绝对路经
            }
        });
        //鼠标监听_目的地址按钮
        aimButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {//鼠标点击
                fileSelect.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//只能选目录,不能选单个文件
                fileSelect.showDialog(panel2,"请选择"+option+"后文件的存放路径");
                File file = fileSelect.getSelectedFile();
                if(file!=null) {
                  //从0开始索引到最后一个空字符串停止
                    String sourceParent = sourceText.getText().substring(0, sourceText.getText().lastIndexOf("\\"));
//                    System.out.println(sourceParent);
                    aimText.setText(file.getAbsolutePath());//目的地址绝对路经
//                    System.out.println("--");
                    if(aimText.getText().equals(sourceText.getText())){//原路径不能等于目的路经
                        JOptionPane.showMessageDialog(MajorFR.this,"文件路径选择不合法,请重新选择!");
                        start.setEnabled(false);
                    }else {
                        start.setEnabled(true);
                    }
                }
            }
        });
        //鼠标监听_开始加密按钮
        start.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {//鼠标点击
              //源地址空/源地址文本为空格(空字符串)/目的地址空/目的地址文本为空格(空字符串)
              //trim:去掉字符串开头和结尾所有空格并返回字符串
                if(sourceText.getText()==null || sourceText.getText().trim().equals("") || aimText.getText()==null || aimText.getText().trim().equals("")) {
                    //提示错误
                  JOptionPane.showMessageDialog(MajorFR.this, "您还没有选择文件呢,请选择您的文件");
                    return;
                }
                //地址赋值
                String sourcePath = sourceText.getText();
                String objPath = aimText.getText();
                boolean isEncryp = false;
                if (option.equals("加密")){
                    isEncryp = true;
                }else if(option.equals("解密")){
                    isEncryp = false;
                }else{
                    JOptionPane.showMessageDialog(MajorFR.this,"程序错误,请重启");
                }
                try {
                    FileAction fileSuperOption = new FileAction();//new一个对象,保证每次的isFirstCopy刚开始都是true!!
                    if (inPassword.getText()==null || inPassword.getText().equals("")) {
                        //不使用密码加密/解密
                        fileSuperOption.superCopy(sourcePath, objPath, isEncryp);
                    }
                    else {
                        //使用密码加密/解密
                        fileSuperOption.superCopy(sourcePath, objPath, isEncryp, inPassword.getText());
                    }
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(MajorFR.this,"路径有误,建议不要手工输入!");
                }
                //JOptionPane.showMessageDialog(CoreFrame.this,option+"成功!");
                int item = JOptionPane.showConfirmDialog(MajorFR.this, option + "成功!是否返回功能首页?");
                if (item==0){
                    MajorFR.this.setVisible(false);//隐藏当前窗体
                    new Index("九芒星_文件加密/解密工具");
                }
            }
        });
        //动作监听器
        selectPassword.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {//事件监听
              String pw;
                if (selectPassword.isSelected()){//是否选中密码按钮组件
                    String password = JOptionPane.showInputDialog(MajorFR.this, "请输入密码:");
                    if (password==null ||password.equals("")){
                        selectPassword.setSelected(false);
                    }               
                    inPassword.setText(password);
                    pw = password;                  
                    System.out.println("输入密码为:"+inPassword.getText());
                    //将密码存放在指定TXT文件
                    String path = "E:\\kkkkk\\文件加密解密\\src\\image\\otr.txt";
                    String word = inPassword.getText();
                    BufferedWriter out = null;
          try {
            out = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(path,true)));
          } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
          }
                    try {
            out.write("   "+word+"   ");
            System.out.println();
          } catch (IOException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
          }
                    try {
            out.close();
          } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
          }                
                    System.out.println("密码已存入otr.txt文件中");
                }else {
                    inPassword.setText("");
//                    System.out.println(inPassword.getText());
                }
            }
        });
    }
    //添加组件
    private void addElements() {
        panel1.add(sourceVersion);//源地址标签面板
        panel1.add(sourceText);//源地址文本框面板
        panel1.add(sourceButton);//源地址按钮面板
        panel2.add(aimVersion);//目的地址标签面板
        panel2.add(aimText);//目的地址文本框面板
        panel2.add(aimButton);//目的地址按钮面板
        panel3.add(selectPassword);//选中密码按钮面板
        panel3.add(selectPasswordText);//选中密码文本面板
        panel3.add(inPassword);//输入密码面板
        panel4.add(start);//开始加(解)密按钮面板
        this.add(panel1);
        this.add(panel2);
        this.add(panel3);
        this.add(panel4);
    }
    //首页组件
    private void setPanelFont() {
        this.setLayout(null);//绝对布局
        this.panel1.setBounds(20,20,500,50);
        this.panel2.setBounds(20,120,500,50);
        this.panel3.setBounds(20,220,500,50);
        this.inPassword.setVisible(false);
        this.panel4.setBounds(20,300,500,50);
    }
    private void setFramePosition() {
        //获得当前屏幕的长宽
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int screenWidth = (int)screenSize.getWidth();
        int screenHeight = (int)screenSize.getHeight();
        //组件位置
        this.setBounds(screenWidth/2-WIDTH/2,screenHeight/2-HEIGHT/2,WIDTH,HEIGHT);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.setVisible(true);
    }
}

6.FileAction类(加密算法)


加密算法为对称加密,自动加索引号并首尾调换位置,可以彻底打乱字节排列顺序,进而产生乱码


举个简单例子,对原始数据89进行加密,很简单,自己参照ASCII表,可以根据加密内容反推原始数据。

对汉字加密,涉及比较复杂。由于字节类型取值范围是-128-127,而UTF-8把Unicode国际编码为0800到FFFF的字符用3字节表示,中文在4E00到9FBF区间内,所以本次加密采用的是三字节表示一个汉字

感兴趣的朋友可以查找对应汉字中文编码,反推数据。对于不深入研究密码学的朋友们来说,意义不大。这里我展示一些汉字中文编码,以供参考。

言归正传,以下是算法实现

package 九芒星加密;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.ImageIcon;
public class FileAction {
    private boolean isFirstCopy = true;
    private boolean goThrough = false;
    private String password = null;
    public void superCopy(String path,String objPath,boolean opFlag,String ...passArgs){
        if (passArgs.length==1){
            goThrough = true;
            password = passArgs[0];
        }
        File file = new File(path);
        String historyFileName = file.getName();
        //首次操作且文件名为1
        if(isFirstCopy && file.isFile()){
          //获取前缀
            String prefix = historyFileName.substring(0, historyFileName.lastIndexOf("."));
            //获取后缀
            String suffix = historyFileName.substring(historyFileName.lastIndexOf("."));
            //加密
            if (opFlag)
                if (historyFileName.contains("解密版"))
                    historyFileName = historyFileName.replace("解密版","加密版");
                else
                    historyFileName = prefix.concat("(加密版)").concat(suffix);
            //解密
            if (!opFlag)
                if (historyFileName.contains("加密版"))
                    historyFileName = historyFileName.replace("加密版","解密版");
                else
                    historyFileName = prefix.concat("(解密版)").concat(suffix);
            isFirstCopy = false;
        }
        //首次操作且路经为1
        if(isFirstCopy && file.isDirectory()){
            if (opFlag) {
                if (historyFileName.contains("解密版"))
                    historyFileName = historyFileName.replace("解密版","加密版");
                else
                    historyFileName = historyFileName.concat("(加密版)");
            }
            if (!opFlag)
                if (historyFileName.contains("加密版"))
                    historyFileName = historyFileName.replace("加密版","解密版");
                else
                    historyFileName = historyFileName.concat("(解密版)");
            isFirstCopy = false;
        }
        String newFilePath = objPath+"\\"+historyFileName;
        File objFile = new File(newFilePath);
        File[] lists = file.listFiles();
        //若list没有地址,在堆内不存在
        if (lists!=null){
            //说明它是一个文件夹
            objFile.mkdir();//在目标路径创建好空的文件夹
            //若堆内有list且不为空
            if (lists.length!=0){
              //遍历list地址
                for(File f:lists){
                    superCopy(f.getAbsolutePath(),objFile.getAbsolutePath(),opFlag);
                }
            }
        //list在堆内存在,说明它是一个文件
        }else{
          //节点流(直接作用于文件)
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream(file);
                fos = new FileOutputStream(objFile);
                byte[] bytes = new byte[1024];
                int count = fis.read(bytes);
                //文件流对文件夹进行递归
                while (count!=-1){//递归整个文件夹
                  //加密
                    if (opFlag){
                        if (count==bytes.length){
                            if(goThrough)
                                fos.write(FileAction.encryptionByPass(bytes,password));//密码加密
                            else
                                fos.write(FileAction.encryption(bytes));//普通加密
                        }else {
                          //拷贝文件
                            byte[] b = new byte[count];
                            for (int i = 0;i<b.length;i++){
                                b[i] = bytes[i];
                            }
                            if(goThrough)
                                fos.write(FileAction.encryptionByPass(b,password));
                            else
                                fos.write(FileAction.encryption(b));
                        }
                    //解密
                    }else {
                        if (count==bytes.length){
                            if(goThrough)
                                fos.write(FileAction.decryptionByPass(bytes,password));
                            else
                                fos.write(FileAction.decryption(bytes));
                        }else {
                          //还原文件
                            byte[] b = new byte[count];
                            for (int i = 0;i<b.length;i++){
                                b[i] = bytes[i];
                            }
                            if(goThrough)
                                fos.write(FileAction.decryptionByPass(b,password));
                            else
                                fos.write(FileAction.decryption(b));
                        }
                    }
                    fos.flush();//清空缓冲区数据,保证缓冲清空输出
                    count = fis.read(bytes);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if (fis!=null) {
                        fis.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (fos!=null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //加密算法
    private static byte[] encryption(byte[] bytes){
      System.out.println("字节总长:"+bytes.length);
      System.out.println();
      //每一个字节的值,都加上它的索引号
        for (int i = 0;i<bytes.length;i++){
          System.out.println("初始bytes["+i+"]:"+bytes[i]+"    加密后bytes["+i+"]:"+(bytes[i]+i));
            bytes[i] = (byte)(bytes[i]+i);           
        }
        //交换第一个字节和最后一个字节的位置
        byte temp = bytes[0];
        bytes[0] = bytes[bytes.length-1];
        bytes[bytes.length-1] = temp;
        System.out.println();
        return bytes;
    }
    //解密算法(加密的逆)
    private static byte[] decryption(byte[] bytes){
      System.out.println("字节总长:"+bytes.length);
      System.out.println();
      //字节首尾交换位置
        byte temp = bytes[0];
        bytes[0] = bytes[bytes.length-1];
        bytes[bytes.length-1] = temp;
        //每一个字节的值,都减去它的索引号
        for (int i = 0;i<bytes.length;i++){
          System.out.println("初始bytes["+i+"]:"+bytes[i]+"    加密后bytes["+i+"]:"+(bytes[i]-i));
            bytes[i] = (byte)(bytes[i]-i);
        }
        System.out.println();
        return bytes;
    }
    //密码加密算法
    public static byte[] encryptionByPass(byte[] bytes,String password){
        byte[] passBytes = encryptionPass(password);       
        //每个字节对整体长度取模
        System.out.println("字节总长:"+bytes.length);
        System.out.println();
        for(int i = 0;i<bytes.length;i++){
          System.out.println("初始bytes["+i+"]:"+bytes[i]+"   →   加密后bytes["+i+"]:"+(byte)(bytes[i]+passBytes[i%passBytes.length]));
            bytes[i] = (byte)(bytes[i]+passBytes[i%passBytes.length]);           
            System.out.println("bytes["+i+"]对应密码长度索引号:"+i%passBytes.length);
            System.out.println("bytes["+i+"]对应密码索引内容:"+passBytes[i%passBytes.length]);
            System.out.println("---------------------------");       
        }
        //字节首尾交换位置
        byte temp = bytes[0];
        bytes[0] = bytes[bytes.length-1];
        bytes[bytes.length-1] = temp;
        System.out.println();
        System.out.println();
        return bytes;         
    }
    //密码解密算法
    public static byte[] decryptionByPass(byte[] bytes,String password){
        byte[] passBytes = encryptionPass(password);
        //字节首尾交换位置
        byte temp = bytes[0];
        bytes[0] = bytes[bytes.length-1];
        bytes[bytes.length-1] = temp;
        //每个字节对整体长度取模
        for (int i = 0;i<bytes.length;i++){
          System.out.println("初始bytes["+i+"]:"+bytes[i]+"   →   解密后bytes["+i+"]:"+(byte)(bytes[i]-passBytes[i%passBytes.length]));
            bytes[i] = (byte)(bytes[i]-passBytes[i%passBytes.length]);            
            System.out.println("bytes["+i+"]对应密码长度索引号:"+i%passBytes.length);
            System.out.println("bytes["+i+"]对应密码索引内容:"+passBytes[i%passBytes.length]);            
            System.out.println("---------------------------");  
        }
        return bytes;
    }
    //使用加密算法,对密码进行二次加密,提高安全性
    private static byte[] encryptionPass(String password){
        byte[] passBytes = password.getBytes();
        //System.out.println("已经二次加密");
        return passBytes;
        //return encryption(encryption(passBytes));
    }
    public static void main(String[] args) {
        FileAction fso = new FileAction();
        String historyFile = "F:\\第一层\\第二层(加密版)";
        String newFile = "F:\\第一层";
        String password = "123456";
        fso.superCopy(historyFile,newFile,false,password);//加密
    }
}

7.Me类(九芒星的博客)


展示相关信息,关注我,获取更多知识。

package 九芒星加密;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Me extends JFrame{
  //创建一个容器
  Container cx;
  //创建背景面板
  BackgroundPanel bg; 
  public static void main(String[] args){
     new Me();
  }
  public Me(){
    cx=this.getContentPane();
    this.setLayout(null);
    setTitle("九芒星_文件加密/解密工具");
    bg=new BackgroundPanel((new ImageIcon("src/image/me.jpg")).getImage());
    bg.setBounds(0,0,419,366);
    cx.add(bg);
    setBounds(660,340,440,400);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
  }
}
  class BG extends JPanel{
    Image i;
    public BG(Image i){
       this.i=i;
       this.setOpaque(true);
    }
    public void paintComponent(Graphics g){
       super.paintComponents(g);
       g.drawImage(i,0,0,this.getWidth(),this.getHeight(),this);
    }
  }

以下是加密效果,对于图片,文字,音频,视频文件都适用。

注:首页中右下角保护隐私按钮,调用的是外部程序,谨慎使用,需要该锁屏程序在评论区留言,私发。

以下是保护隐私按钮的效果图

目录
相关文章
|
1天前
|
数据采集 前端开发 Java
Java医院绩效考核系统源码maven+Visual Studio Code一体化人力资源saas平台系统源码
医院绩效解决方案包括医院绩效管理(BSC)、综合奖金核算(RBRVS),涵盖从绩效方案的咨询与定制、数据采集、绩效考核及反馈、绩效奖金核算到科到组、分配到员工个人全流程绩效管理;将医院、科室、医护人员利益绑定;全面激活人才活力;兼顾质量和效益、长期与短期利益;助力医院降本增效,持续改善、优化收入、成本结构。
4 0
|
1天前
|
Java
排课系统【JSP+Servlet+JavaBean】(Java课设)
排课系统【JSP+Servlet+JavaBean】(Java课设)
13 5
|
2天前
|
存储 Java API
java对接IPFS系统-以nft.storage为列
java对接IPFS系统-以nft.storage为列
11 2
|
2天前
|
Java 开发者
Java一分钟之-Java IO流:文件读写基础
【5月更文挑战第10天】本文介绍了Java IO流在文件读写中的应用,包括`FileInputStream`和`FileOutputStream`用于字节流操作,`BufferedReader`和`PrintWriter`用于字符流。通过代码示例展示了如何读取和写入文件,强调了常见问题如未关闭流、文件路径、编码、权限和异常处理,并提供了追加写入与读取的示例。理解这些基础知识和注意事项能帮助开发者编写更可靠的程序。
8 0
|
2天前
|
监控 前端开发 Java
Java基于B/S医院绩效考核管理平台系统源码 医院智慧绩效管理系统源码
医院绩效考核系统是一个关键的管理工具,旨在评估和优化医院内部各部门、科室和员工的绩效。一个有效的绩效考核系统不仅能帮助医院实现其战略目标,还能提升医疗服务质量,增强患者满意度,并促进员工的专业成长
9 0
|
2天前
|
Java 云计算
Java智能区域医院云HIS系统SaaS源码
云HIS提供标准化、信息化、可共享的医疗信息管理系统,实现医患事务管理和临床诊疗管理等标准医疗管理信息系统的功能。优化就医、管理流程,提升患者满意度、基层首诊率,通过信息共享、辅助诊疗等手段,提高基层医生的服务能力构建和谐的基层医患关系。
16 2
|
3天前
|
Java
JDK环境下利用记事本对java文件进行运行编译
JDK环境下利用记事本对java文件进行运行编译
10 0
|
3天前
|
前端开发 Java 关系型数据库
Java医院绩效考核系统源码B/S架构+springboot三级公立医院绩效考核系统源码 医院综合绩效核算系统源码
作为医院用综合绩效核算系统,系统需要和his系统进行对接,按照设定周期,从his系统获取医院科室和医生、护士、其他人员工作量,对没有录入信息化系统的工作量,绩效考核系统设有手工录入功能(可以批量导入),对获取的数据系统按照设定的公式进行汇算,且设置审核机制,可以退回修正,系统功能强大,完全模拟医院实际绩效核算过程,且每步核算都可以进行调整和参数设置,能适应医院多种绩效核算方式。
22 2
|
4天前
|
JavaScript 小程序 Java
基于java的少儿编程网上报名系统
基于java的少儿编程网上报名系统
11 2
|
存储 算法 前端开发
一文带你学会国产加密算法SM4的java实现方案
今天给大家带来一个国产SM4加密解密算法的java后端解决方案,代码完整,可以直接使用,希望给大家带来帮助,尤其是做政府系统的开发人员,可以直接应用到项目中进行加密解密。
2402 1