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


具体使用方法如下:

  1. import java.io.File;
  2. import java.io.IOException;
  3. import java.util.zip.DataFormatException;
  4. import de.idyl.winzipaes.AesZipFileDecrypter;
  5. import de.idyl.winzipaes.AesZipFileEncrypter;
  6. import de.idyl.winzipaes.impl.AESDecrypterBC;
  7. import de.idyl.winzipaes.impl.AESEncrypterBC;
  8. import de.idyl.winzipaes.impl.ExtZipEntry;
  9. /**
  10. *
  11. * @author Jerry.tao
  12. *
  13. */
  14. public class FileUtil {
  15. /**
  16. * 压缩单个文件并加密
  17. * @param srcFile 待压缩的文件
  18. * @param desFileName 生成的目标文件
  19. * @param passWord 压缩文件加密密码
  20. * @throws IOException
  21. */
  22. public static void zipFile(String srcFile,String desFile,String passWord) throws IOException{
  23. AesZipFileEncrypter.zipAndEncrypt(new File(srcFile),new File(desFile), passWord, new AESEncrypterBC());
  24. }
  25. /**
  26. * 给指定的压缩文件进行加密
  27. * @param srcZipFile 待加密的压缩文件
  28. * @param desFile 加密后的目标压缩文件
  29. * @param passWord 压缩文件加密密码
  30. * @throws IOException
  31. */
  32. public static void encryptZipFile(String srcZipFile,String desFile,String passWord) throws IOException{
  33. AesZipFileEncrypter.zipAndEncryptAll(new File(srcZipFile), new File(desFile), passWord, new AESEncrypterBC());
  34. }
  35. /**
  36. * 解密抽取压缩文件中的某个文件
  37. * @param srcZipFile 加密的压缩文件
  38. * @param extractFileName 抽取压缩文件中的某个文件的名称
  39. * @param desFile 解压后抽取后生成的目标文件
  40. * @param passWord 解压密码
  41. * @throws IOException
  42. * @throws DataFormatException
  43. */
  44. public static void decrypterZipFile(String srcZipFile,String extractFileName,String desFile,String passWord)throws IOException, DataFormatException{
  45. AesZipFileDecrypter zipFile = new AesZipFileDecrypter( new File(srcZipFile),new AESDecrypterBC());
  46. ExtZipEntry entry = zipFile.getEntry(extractFileName);
  47. zipFile.extractEntry( entry, new File(desFile),passWord);
  48. }
  49. public static void main(String[] args) throws Exception {
  50. String srcFile="doc/zip_test/1_admin_work.xlsx";
  51. String desFile="doc/zip_test/1_admin_work_Encrypter.zip";
  52. FileUtil.zipFile(srcFile, desFile,"123456");
  53. String srcZipFile="doc/zip_test/work.zip";
  54. String desZipFile="doc/zip_test/work_Encrypter.zip";
  55. FileUtil.encryptZipFile(srcZipFile, desZipFile,"123456");
  56. String decrypterSrcZipFile="doc/zip_test/work_Encrypter.zip";
  57. String extractFileName="1.xlsx";
  58. String decrypterDesFile="doc/zip_test/1_decrypter.xlsx";
  59. FileUtil.decrypterZipFile(decrypterSrcZipFile,extractFileName, decrypterDesFile,"123456");
  60. }
  61. }