通过Java对文件进行压缩加密我一般都使用winzipaes工具包,该工具包支持AES压缩和解压zip文件,首先通过http://code.google.com/p/winzipaes/downloads/list可以下载对应版本的源码,然后通过http://www.bouncycastle.org/latest_releases.html地址下载winzipaes依赖包,手工将winzipaes源码打成Jar包即可使用。
具体使用方法如下:
- 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");
- }
- }