Java Swing 调用接口实现对文件的AES加解密

  程序调用的是Java crypto接口,是为cryptographic操作提供类和接口,这个包中定义的cryptographic操作包括加密、密钥生成和密钥协商,以及消息验证代码(MAC)生成,程序运行的结果图如下:

话不多说,直接上代码

首先是实现加解密的AESUtil.class

package Jframe;

/**
 * Created by hua on 2017/6/30.
 */

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {
    //初始化向量,aes 16位
    private static final String IV = "abcdefghijk1mnop";

    //二进制转变为16进制
    public static String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    //将16进制转变为二进制
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    //加密
    public static String encrypt(String content, String keyWord) throws Exception {
        try {
            SecretKeySpec key = new SecretKeySpec(keyWord.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes()));
            byte[] encryptedData = cipher.doFinal(content.getBytes("UTF-8"));
            return parseByte2HexStr(encryptedData);
        } catch (Exception e) {
            throw new Exception("加密失败");
        }
    }

    //解密
    public static String decrypt(String content, String keyWord) throws Exception {
        byte[] contentBytes = parseHexStr2Byte(content);
        try {
            SecretKeySpec key = new SecretKeySpec(keyWord.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes()));
            byte[] result = cipher.doFinal(contentBytes);
            return new String(result, "UTF-8");
        } catch (Exception e) {
            throw new Exception("解密失败");
        }
    }

    public static void main(String[] args) throws Exception {

        String content = "长风破浪会有时,直挂云帆济沧海!";
        String password = "0123456789abcdef";   //使用AES-128-CBC加密模式,key需要为16位

        System.out.println("加密前:" + content);
        String encryptResult = AESUtil.encrypt(content, password);
        System.out.println("加密后:" + encryptResult);
        String decryptResult = AESUtil.decrypt(encryptResult,password);
        System.out.println("解密后:" + decryptResult);
    }
}

然后是界面

package Jframe;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField; 


public class Jframe1 extends JFrame implements ActionListener{

    private File lockfile;
    private File unlockfile;
    private String temp1;
    

    JButton jb1,jb2,jb3,jb4,jb5;
    JLabel jlb1,jlb2,jlb3;
    JPanel jp1,jp2,jp3,jp4,jp5;
    JTextField jtf1,jtf2,jtf3,jtf4;
    
    public Jframe1(){
        
        jb1=new JButton("加密文件");
        jb2=new JButton("解密文件");
        jb3=new JButton("退出");
        jb4=new JButton("...");
        jb5=new JButton("...");
        
        jb1.addActionListener(this);
        jb2.addActionListener(this);
        jb3.addActionListener(this);
        jb4.addActionListener(this);
        jb5.addActionListener(this);
        
        
        jlb1=new JLabel("选择加密文件:");
        jlb2=new JLabel("口令");
        jlb3=new JLabel("选择解密文件:");
        
        
        jtf1=new JTextField(10);
        jtf2=new JTextField(10);
        jtf2.setText("请输入16位Key");
        jtf3=new JTextField(10);
        
        jp1=new JPanel();
        jp2=new JPanel();
        jp3=new JPanel();
        jp5=new JPanel();
        
        jp1.add(jlb1);
        jp1.add(jtf1);
        jp1.add(jb4);
        
        jp2.add(jlb2);
        jp2.add(jtf2);
        
        jp3.add(jlb3);
        jp3.add(jtf3);
        jp3.add(jb5);
        
        
        jp5.add(jb1);
        jp5.add(jb2);
        jp5.add(jb3);

        this.add(jp1);
        this.add(jp2);
        this.add(jp3);
        this.add(jp5);
        
        this.setLayout(new GridLayout(5,1));
        this.setTitle("文件AES加解密程序");
        this.setBounds(300, 200, 400, 320);
        this.setResizable(false);
        this.setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    
        
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new Jframe1();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        
        //监听按钮
        if(e.getActionCommand()=="退出"){
            System.exit(0);
        }
        if(e.getActionCommand()=="加密文件"){
            try {
                this.lock();
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        if(e.getActionCommand()=="解密文件"){
            try {
                this.unlock();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        if(e.getSource()==jb4){
            JFileChooser jfc=new JFileChooser();
            jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
            jfc.showDialog(new JLabel(), "选择");
            lockfile=jfc.getSelectedFile();
            jtf1.setText(lockfile.getName());
        }
        if(e.getSource()==jb5){
            JFileChooser jfc=new JFileChooser();
            jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
            jfc.showDialog(new JLabel(), "选择");
            unlockfile=jfc.getSelectedFile();
            jtf3.setText(unlockfile.getName());
            }
        }
        

    
    //加密
    public void lock() throws Exception{
        int buffersize=1024,length;
        String path,addpath=".e";
        char[] buffer=new char[buffersize];
        StringBuffer out=new StringBuffer();
        InputStream is = new FileInputStream(lockfile.getPath().toString());
        Reader in = new InputStreamReader(is, "UTF-8");
        String context;
        for (; ; ) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
        context=out.toString();
        temp1=AESUtil.encrypt(context, jtf2.getText().toString());
        path=lockfile.getAbsolutePath();
        length=path.length();
        addpath=path.substring(0, length)+addpath;
        File fout=new File(addpath);
        FileOutputStream fos=new FileOutputStream(fout);
        BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(fos));
        bw.write(temp1);
        JOptionPane.showMessageDialog(this, "加密成功");
        bw.close();
    }

    
    //解密
    public void unlock() throws Exception{
        int buffersize=1024,length;
        String path,addpath=".e";
        char[] buffer=new char[buffersize];
        StringBuffer out=new StringBuffer();
        InputStream is = new FileInputStream(unlockfile.getPath().toString());
        Reader in = new InputStreamReader(is, "UTF-8");
        String context;
        for (; ; ) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
        context=out.toString();
        temp1=AESUtil.decrypt(context, jtf2.getText().toString());
        path=unlockfile.getAbsolutePath();
        length=path.length();
        addpath=path.substring(0, length-2);
        File fout=new File(addpath);
        FileOutputStream fos=new FileOutputStream(fout);
        BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(fos));
        bw.write(temp1);
        JOptionPane.showMessageDialog(this, "解密成功");
        bw.close();
    }
    
}

  关于这个接口的更多信息,自行百度吧

 

posted @ 2019-03-16 15:11  羽吢  阅读(507)  评论(0)    收藏  举报