經過Java生成加密壓縮文件(支持AES壓縮和解壓zip文件)

  經過Java對文件進行壓縮加密我通常都使用winzipaes工具包,該工具包支持AES壓縮和解壓zip文件,首先經過http://code.google.com/p/winzipaes/downloads/list能夠下載對應版本的源碼,而後經過http://www.bouncycastle.org/latest_releases.html地址下載winzipaes依賴包,手工將winzipaes源碼打成Jar包便可使用。html


具體使用方法以下:java

import java.io.File;
import java.io.IOException;
import java.util.zip.DataFormatException;
import de.idyl.winzipaes.AesZipFileDecrypter;
import de.idyl.winzipaes.AesZipFileEncrypter;
import de.idyl.winzipaes.impl.AESDecrypterBC;
import de.idyl.winzipaes.impl.AESEncrypterBC;
import de.idyl.winzipaes.impl.ExtZipEntry;
/**
 *
 * @author Jerry.tao
 *
 */
public class FileUtil {
    /**
     * 壓縮單個文件並加密
     * @param srcFile      待壓縮的文件
     * @param desFileName  生成的目標文件
     * @param passWord     壓縮文件加密密碼
     * @throws IOException
     */
    public static void zipFile(String srcFile,String desFile,String passWord) throws IOException{
        AesZipFileEncrypter.zipAndEncrypt(new File(srcFile),new File(desFile), passWord, new AESEncrypterBC());
    }
                      
    /**
     * 給指定的壓縮文件進行加密
     * @param srcZipFile      待加密的壓縮文件
     * @param desFile         加密後的目標壓縮文件
     * @param passWord        壓縮文件加密密碼
     * @throws IOException
     */
    public static void encryptZipFile(String srcZipFile,String desFile,String passWord) throws IOException{
        AesZipFileEncrypter.zipAndEncryptAll(new File(srcZipFile), new File(desFile), passWord, new AESEncrypterBC());
    }
                      
    /**
     * 解密抽取壓縮文件中的某個文件
     * @param srcZipFile    加密的壓縮文件
     * @param extractFileName  抽取壓縮文件中的某個文件的名稱
     * @param desFile          解壓後抽取後生成的目標文件
     * @param passWord         解壓密碼
     * @throws IOException
     * @throws DataFormatException
     */
    public static void  decrypterZipFile(String srcZipFile,String extractFileName,String desFile,String passWord)throws IOException, DataFormatException{
        AesZipFileDecrypter zipFile = new AesZipFileDecrypter( new File(srcZipFile),new  AESDecrypterBC());
        ExtZipEntry entry = zipFile.getEntry(extractFileName);
        zipFile.extractEntry( entry, new File(desFile),passWord);
    }
                      
    public static void main(String[] args) throws Exception {
        String srcFile="doc/zip_test/1_admin_work.xlsx";
        String desFile="doc/zip_test/1_admin_work_Encrypter.zip";
        FileUtil.zipFile(srcFile, desFile,"123456");
                          
        String srcZipFile="doc/zip_test/work.zip";
        String desZipFile="doc/zip_test/work_Encrypter.zip";
        FileUtil.encryptZipFile(srcZipFile, desZipFile,"123456");
                          
        String decrypterSrcZipFile="doc/zip_test/work_Encrypter.zip";
        String extractFileName="1.xlsx";
        String decrypterDesFile="doc/zip_test/1_decrypter.xlsx";
        FileUtil.decrypterZipFile(decrypterSrcZipFile,extractFileName, decrypterDesFile,"123456");
    }
}
相關文章
相關標籤/搜索