Java 文件(夹)加密解密工具(附带压缩功能)

版权声明:[email protected] https://blog.csdn.net/zhaoxuyang1997/article/details/81636527

1 使用说明

图1 主界面
图1 主界面


图2 加密-选择文件或文件夹的输入路径
图2 加密-选择文件或文件夹的输入路径


图3 选择加密文件的输出路径
图3 选择加密文件的输出路径


图4 加密结果
图4 加密结果


图5 加密前的math文件夹与加密后的new.zxy97文件的比较
图5 加密前的math文件夹与加密后的new.zxy97文件的比较


图6 解密-选择加密文件new.zxy97
图6 解密-选择加密文件new.zxy97


图7 解密-选择解密后的生成文件所在的文件夹
图7 解密-选择解密后的生成文件所在的文件夹


图8 解密结果
图8 解密结果


图9 加密前的文件夹与加密又解密后生成的文件夹的比较
图9 加密前的文件夹与加密又解密后生成的文件夹的比较


图10 工程结构图
图10 工程结构图


CipherUtil.java


/**
 * CipherUtil.java 
 */
package com.zxy97.jiami;

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.OutputStream;   
import java.security.GeneralSecurityException;   
import java.security.Key;   
import java.security.SecureRandom;   
import javax.crypto.Cipher;   
import javax.crypto.KeyGenerator;   
import javax.crypto.SecretKey;   

/**  
 * 使用AES对文件进行加密和解密  
 *  
 */  
public class CipherUtil {   
    /**  
     * 使用AES对文件进行加密和解密  
     *   
     */  
    private static String type = "AES";   

    /**  
     * 把文件srcFile加密后存储为destFile  
     * @param srcFile     加密前的文件  
     * @param destFile    加密后的文件  
     * @param privateKey  密钥  
     * @throws GeneralSecurityException  
     * @throws IOException  
     */  
    public void encrypt(String srcFile, String destFile, String privateKey) throws GeneralSecurityException, IOException {   
        Key key = getKey(privateKey);   
        Cipher cipher = Cipher.getInstance(type + "/ECB/PKCS5Padding");   
        cipher.init(Cipher.ENCRYPT_MODE, key);   

        FileInputStream fis = null;   
        FileOutputStream fos = null;   
        try {   
            fis = new FileInputStream(srcFile);   
            fos = new FileOutputStream(mkdirFiles(destFile));   

            crypt(fis, fos, cipher);   
        } catch (FileNotFoundException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        } finally {   
            if (fis != null) {   
                fis.close();   
            }   
            if (fos != null) {   
                fos.close();   
            }   
        }   
    }   

    /**  
     * 把文件srcFile解密后存储为destFile  
     * @param srcFile     解密前的文件  
     * @param destFile    解密后的文件  
     * @param privateKey  密钥  
     * @throws GeneralSecurityException  
     * @throws IOException  
     */  
    public void decrypt(String srcFile, String destFile, String privateKey) throws GeneralSecurityException, IOException {   
        Key key = getKey(privateKey);   
        Cipher cipher = Cipher.getInstance(type + "/ECB/PKCS5Padding");   
        cipher.init(Cipher.DECRYPT_MODE, key);   

        FileInputStream fis = null;   
        FileOutputStream fos = null;   
        try {   
            fis = new FileInputStream(srcFile);   
            fos = new FileOutputStream(mkdirFiles(destFile));   

            crypt(fis, fos, cipher);   
        } catch (FileNotFoundException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        } finally {   
            if (fis != null) {   
                fis.close();   
            }   
            if (fos != null) {   
                fos.close();   
            }   
        }   
    }   

    /**  
     * 根据filePath创建相应的目录  
     * @param filePath      要创建的文件路经  
     * @return  file        文件  
     * @throws IOException  
     */  
    private File mkdirFiles(String filePath) throws IOException {   
        File file = new File(filePath);   
        if (!file.getParentFile().exists()) {   
            file.getParentFile().mkdirs();   
        }   
        file.createNewFile();   

        return file;   
    }   

    /**  
     * 生成指定字符串的密钥  
     * @param secret        要生成密钥的字符串  
     * @return secretKey    生成后的密钥  
     * @throws GeneralSecurityException  
     */  
    private static Key getKey(String secret) throws GeneralSecurityException {   
        KeyGenerator kgen = KeyGenerator.getInstance(type);   
        kgen.init(128, new SecureRandom(secret.getBytes()));   
        SecretKey secretKey = kgen.generateKey();   
        return secretKey;   
    }   

    /**  
     * 加密解密流  
     * @param in        加密解密前的流  
     * @param out       加密解密后的流  
     * @param cipher    加密解密  
     * @throws IOException  
     * @throws GeneralSecurityException  
     */  
    private static void crypt(InputStream in, OutputStream out, Cipher cipher) throws IOException, GeneralSecurityException {   
        int blockSize = cipher.getBlockSize() * 1000;   
        int outputSize = cipher.getOutputSize(blockSize);   

        byte[] inBytes = new byte[blockSize];   
        byte[] outBytes = new byte[outputSize];   

        int inLength = 0;   
        boolean more = true;   
        while (more) {   
            inLength = in.read(inBytes);   
            if (inLength == blockSize) {   
                int outLength = cipher.update(inBytes, 0, blockSize, outBytes);   
                out.write(outBytes, 0, outLength);   
            } else {   
                more = false;   
            }   
        }   
        if (inLength > 0)   
            outBytes = cipher.doFinal(inBytes, 0, inLength);   
        else  
            outBytes = cipher.doFinal();   
        out.write(outBytes);   
    }   
}

ZipUtil.java


/**
 * ZipUtil.java 
 */


package com.zxy97.jiami;

import java.io.File;   
import java.io.FileInputStream;   
import java.io.FileOutputStream;   
import java.io.IOException;   
import java.util.zip.ZipEntry;   
import java.util.zip.ZipInputStream;   
import java.util.zip.ZipOutputStream;   

/**  
 * 对文件或文件夹进行压缩和解压  
 *  
 */  
public class ZipUtil {   
    /**得到当前系统的分隔符*/  
//  private static String separator = System.getProperty("file.separator");   

    /**  
     * 添加到压缩文件中  
     * @param out  
     * @param f  
     * @param base  
     * @throws Exception  
     */  
    private void directoryZip(ZipOutputStream out, File f, String base) throws Exception {   
        // 如果传入的是目录   
        if (f.isDirectory()) {   
            File[] fl = f.listFiles();   
            // 创建压缩的子目录   
            out.putNextEntry(new ZipEntry(base + "/"));   
            if (base.length() == 0) {   
                base = "";   
            } else {   
                base = base + "/";   
            }   
            for (int i = 0; i < fl.length; i++) {   
                directoryZip(out, fl[i], base + fl[i].getName());   
            }   
        } else {   
            // 把压缩文件加入rar中   
            out.putNextEntry(new ZipEntry(base));   
            FileInputStream in = new FileInputStream(f);   
            byte[] bb = new byte[10240];   
            int aa = 0;   
            while ((aa = in.read(bb)) != -1) {   
                out.write(bb, 0, aa);   
            }   
            in.close();   
        }   
    }   

    /**  
     * 压缩文件  
     *   
     * @param zos  
     * @param file  
     * @throws Exception  
     */  
    private void fileZip(ZipOutputStream zos, File file) throws Exception {   
        if (file.isFile()) {   
            zos.putNextEntry(new ZipEntry(file.getName()));   
            FileInputStream fis = new FileInputStream(file);   
            byte[] bb = new byte[10240];   
            int aa = 0;   
            while ((aa = fis.read(bb)) != -1) {   
                zos.write(bb, 0, aa);   
            }   
            fis.close();   
            System.out.println(file.getName());   
        } else {   
            directoryZip(zos, file, "");   
        }   
    }   

    /**  
     * 解压缩文件  
     *   
     * @param zis  
     * @param file  
     * @throws Exception  
     */  
    private void fileUnZip(ZipInputStream zis, File file) throws Exception {   
        ZipEntry zip = zis.getNextEntry();   
        if (zip == null)   
            return;   
        String name = zip.getName();   
        File f = new File(file.getAbsolutePath() + "/" + name);   
        if (zip.isDirectory()) {   
            f.mkdirs();   
            fileUnZip(zis, file);   
        } else {   
            f.createNewFile();   
            FileOutputStream fos = new FileOutputStream(f);   
            byte b[] = new byte[10240];   
            int aa = 0;   
            while ((aa = zis.read(b)) != -1) {   
                fos.write(b, 0, aa);   
            }   
            fos.close();   
            fileUnZip(zis, file);   
        }   
    }   

    /**  
     * 根据filePath创建相应的目录  
     * @param filePath  
     * @return  
     * @throws IOException  
     */  
    private File mkdirFiles(String filePath) throws IOException{   
        File file = new File(filePath);   
        if(!file.getParentFile().exists()){   
            file.getParentFile().mkdirs();   
        }   
        file.createNewFile();   

        return file;   
    }   

    /**  
     * 对zipBeforeFile目录下的文件压缩,保存为指定的文件zipAfterFile  
     *   
     * @param zipBeforeFile     压缩之前的文件  
     * @param zipAfterFile      压缩之后的文件  
     */  
    public void zip(String zipBeforeFile, String zipAfterFile) {   
        try {   

            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(mkdirFiles(zipAfterFile)));   
            fileZip(zos, new File(zipBeforeFile));   
            zos.close();   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   

    /**  
     * 解压缩文件unZipBeforeFile保存在unZipAfterFile目录下  
     *   
     * @param unZipBeforeFile       解压之前的文件  
     * @param unZipAfterFile        解压之后的文件  
     */  
    public void unZip(String unZipBeforeFile, String unZipAfterFile) {   
        try {   
            ZipInputStream zis = new ZipInputStream(new FileInputStream(unZipBeforeFile));   
            File f = new File(unZipAfterFile);   
            f.mkdirs();   
            fileUnZip(zis, f);   
            zis.close();   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   
} 

ZipCipherUtil.java


 /**
 * ZipCipherUtil.java 
 */
package com.zxy97.jiami;

import java.io.File;     
import java.util.UUID;     

public class ZipCipherUtil {     
    /**   
     * 对目录srcFile下的所有文件目录进行先压缩后加密,然后保存为destfile   
     *    
     * @param srcFile 要操作的文件或文件夹   
     * @param destfile 压缩加密后存放的文件   
     * @param keyStr 密钥   
     */    
    public static void encryptZip(String srcFile, String destfile, String keyStr) throws Exception {     
        File temp = new File(UUID.randomUUID().toString() + ".zip");     
        temp.deleteOnExit();     
        // 先压缩文件      
        new ZipUtil().zip(srcFile, temp.getAbsolutePath());     
        // 对文件加密      
        new CipherUtil().encrypt(temp.getAbsolutePath(), destfile, keyStr);     
        temp.delete();     
    }     

    /**   
     * 对文件srcfile进行先解密后解压缩,然后解压缩到目录destfile下   
     *    
     * @param srcfile 要解密和解压缩的文件名    
     * @param destfile 解压缩后的目录   
     * @param keyStr  密钥   
     */    
    public static void decryptUnzip(String srcfile, String destfile, String keyStr) throws Exception {     
        File temp = new File(UUID.randomUUID().toString() + ".zip");     
        temp.deleteOnExit();     
        // 先对文件解密      
        new CipherUtil().decrypt(srcfile, temp.getAbsolutePath(), keyStr);     
        // 解压缩      
        new ZipUtil().unZip(temp.getAbsolutePath(),destfile);     
        temp.delete();     
    }     
    public static final String FILE_NAME_EXTENSION = "zxy97";
    public static void main(String[] args) throws Exception {     
        long l1 = System.currentTimeMillis();        
        //加密      
        new ZipCipherUtil().encryptZip("d:\\soft", "d:\\yaxin.zip", "123");      
        //解密      
        new ZipCipherUtil().decryptUnzip("d:\\yaxin.zip", "d:\\yaxin2", "123");     

        long l2 = System.currentTimeMillis();     
        System.out.println((l2 - l1) + "毫秒.");     
        System.out.println(((l2 - l1) / 1000) + "秒.");
    }     
}    

FileUtil.java


/*
 * FileUtil.java
 */

package com.zxy97.jiami;

import java.text.DecimalFormat;

public class FileUtil {
    public static String getFileSize(long length){
        DecimalFormat df = new DecimalFormat("#.00");
        String str;
        if(length<=0){
           str = "";
        }else if(length<1024){
           str = df.format(length)+"B";
        }else if(length<1024*1024){
            str = df.format((length/1024.0)) + "KB"; 
        }else if(length<1024*1024*1024){
            str = df.format((length/1024.0/1024)) + "MB"; 
        }else{
            str = df.format((length/1024.0/1024/1024)) + "GB"; 
        }
        return str;
    }
}

FrmMain.java

/*
 * FrmMain.java
 */

package com.zxy97.jiami;

import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;


public class FrmMain extends javax.swing.JFrame {


    public FrmMain() {
        setResizable(false);
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jTextField5 = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jButton4 = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        jTextField6 = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jButton5 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel13 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("文件(夹)加密解密工具");

        jLabel1.setText("1. 输入路径:");

        jButton1.setFont(new java.awt.Font("微软雅黑", 0, 15)); // NOI18N
        jButton1.setText("文件(夹)");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText("2. 设置密码:");

        jLabel3.setText("3. 开始加密:");

        jButton2.setText("开始加密");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel4.setText("4. 输出路径:");

        jLabel6.setFont(new java.awt.Font("宋体", 1, 15)); // NOI18N
        jLabel6.setText("加密");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 298, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2)
                        .addGap(42, 42, 42)
                        .addComponent(jLabel5))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel6))
                .addGap(20, 20, 20))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel7.setText("5. 输入路径:");

        jLabel8.setText("6. 设置密码:");

        jLabel9.setText("7. 开始解密:");

        jButton4.setText("开始解密");
        jButton4.setActionCommand("开始解密");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jLabel10.setText("8. 输出路径:");

        jLabel12.setFont(new java.awt.Font("宋体", 1, 15)); // NOI18N
        jLabel12.setText("解密");

        jButton5.setFont(new java.awt.Font("微软雅黑", 0, 15)); // NOI18N
        jButton5.setText("文件");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 298, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel10)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel12)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton4)
                        .addGap(42, 42, 42)
                        .addComponent(jLabel11)))
                .addGap(24, 24, 24))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel12)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton4)
                    .addComponent(jLabel9)
                    .addComponent(jLabel11))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(60, 60, 60))
        );

        jLabel13.setFont(new java.awt.Font("微软雅黑 Light", 0, 12)); // NOI18N
        jLabel13.setText("文件(夹)加密解密工具 | 版权所有 zxy97.com | 2018-07-24 02:00 ~ 07:12");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 445, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(24, 24, 24))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // 1. 输入路径 加密-文件选择对话框
        JFileChooser jfc = new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        jfc.showOpenDialog(null);
        File file1 = jfc.getSelectedFile();
        if(file1 != null){
            jTextField1.setText(file1.getAbsolutePath());
        }
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // 3. 开始加密
        String fne = ZipCipherUtil.FILE_NAME_EXTENSION;
        File file1 = new File(jTextField1.getText());
        if(file1.exists()){
            JFileChooser jfc = new JFileChooser();
            jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
            jfc.setToolTipText("选择加密到到哪个文件中");
            jfc.setName(file1.getName()+"."+fne);
            jfc.setFileFilter(new FileNameExtensionFilter(fne, fne));
            jfc.showSaveDialog(null);
            File file4 = jfc.getSelectedFile();
            if(file4 != null){
                String fOutPath = file4.getAbsolutePath();
                if(!fOutPath.endsWith("."+fne)){
                    fOutPath += "." + fne;
                }
                jTextField3.setText(fOutPath);
                long l1 = System.currentTimeMillis();              
                try {
                    ZipCipherUtil.encryptZip(jTextField1.getText(), fOutPath, jTextField2.getText());
                } catch (Exception ex) {
                    jLabel5.setText("系统出现异常,导致加密失败!");
                    Logger.getLogger(FrmMain.class.getName()).log(Level.SEVERE, null, ex);
                }
                long l2 = System.currentTimeMillis();
                jLabel5.setText("加密成功!用时:"+(l2 - l1) + "毫秒");
            }else{
                jLabel5.setText("您没有选择加密后输出文件的路径,请点击【开始加密】后重新选择!");
            }
        }

    }                                        

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // 5. 解密 选择文件对话框
        String fne = ZipCipherUtil.FILE_NAME_EXTENSION;
        JFileChooser jfc = new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jfc.setFileFilter(new FileNameExtensionFilter(fne, fne));
        jfc.showOpenDialog(null);
        File file4 = jfc.getSelectedFile();
        if(file4 != null){
            jTextField4.setText(file4.getAbsolutePath());
        }
    }                                        

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // 7. 开始解密
        String fne = ZipCipherUtil.FILE_NAME_EXTENSION;
        File file4 = new File(jTextField4.getText());
        if(file4.exists()){
            JFileChooser jfc = new JFileChooser();
            jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            jfc.setToolTipText("选择解密到哪个文件夹下");
            jfc.showSaveDialog(null);
            File file6 = jfc.getSelectedFile();
            if(file6 != null){
                String fOutPath = file6.getAbsolutePath();
                jTextField6.setText(fOutPath);
                long l1 = System.currentTimeMillis();              
                try {
                    ZipCipherUtil.decryptUnzip(jTextField4.getText(), fOutPath, jTextField5.getText());
                } catch (Exception ex) {
                    jLabel11.setText("系统出现异常,导致加密失败!");
                    Logger.getLogger(FrmMain.class.getName()).log(Level.SEVERE, null, ex);
                }
                long l2 = System.currentTimeMillis();
                jLabel11.setText("解密成功!用时:"+(l2 - l1) + "毫秒");
            }else{
                jLabel11.setText("您没有选择解密后输出文件的路径,请点击【开始解密】后重新选择!");
            }
        }
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html ;
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmMain().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    // End of variables declaration                   
}

猜你喜欢

转载自blog.csdn.net/zhaoxuyang1997/article/details/81636527