Java对文件压缩/加密/解密/解压缩的例子,DES/RSA

RSA压缩加密/解压缩解密
  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.ObjectInputStream;
  5. import java.io.ObjectOutputStream;
  6. import java.security.Key;
  7. import java.security.KeyPair;
  8. import java.security.KeyPairGenerator;
  9. import java.security.PrivateKey;
  10. import java.security.PublicKey;
  11. import java.security.SecureRandom;
  12. import java.util.Properties;
  13. import java.util.UUID;
  14. import java.util.zip.ZipEntry;
  15. import java.util.zip.ZipInputStream;
  16. import java.util.zip.ZipOutputStream;

  17. import javax.crypto.Cipher;

  18. /**
  19.  * 对文件压缩加密/解密解压缩 对象类
  20.  *
  21.  */
  22. public class ZipEncrypt {
  23.  private static PrivateKey privateKey;
  24.  private static PublicKey publicKey;
  25.  private static void directoryZip(ZipOutputStream out, File f, String base)
  26.    throws Exception {
  27.   // 如果传入的是目录
  28.   if (f.isDirectory()) {
  29.    File[] fl = f.listFiles();
  30.    // 创建压缩的子目录
  31.    out.putNextEntry(new ZipEntry(base + "/"));
  32.    if (base.length() == 0) {
  33.     base = "";
  34.    } else {
  35.     base = base + "/";
  36.    }
  37.    for (int i = 0; i < fl.length; i++) {
  38.     directoryZip(out, fl[i], base + fl[i].getName());
  39.    }
  40.   } else {
  41.    // 把压缩文件加入rar中
  42.    out.putNextEntry(new ZipEntry(base));
  43.    FileInputStream in = new FileInputStream(f);
  44.    byte[] bb = new byte[2048];
  45.    int aa = 0;
  46.    while ((aa = in.read(bb)) != -1) {
  47.     out.write(bb, 0, aa);
  48.    }
  49.    in.close();
  50.   }
  51.  }

  52.  /**
  53.   * 压缩文件
  54.   * @param zos
  55.   * @param file
  56.   * @throws Exception
  57.   */
  58.  private static void fileZip(ZipOutputStream zos, File file)
  59.    throws Exception {
  60.   if (file.isFile()) {
  61.    zos.putNextEntry(new ZipEntry(file.getName()));
  62.    FileInputStream fis = new FileInputStream(file);
  63.    byte[] bb = new byte[2048];
  64.    int aa = 0;
  65.    while ((aa = fis.read(bb)) != -1) {
  66.     zos.write(bb, 0, aa);
  67.    }
  68.    fis.close();
  69.    System.out.println(file.getName());
  70.   } else {
  71.    directoryZip(zos, file, "");
  72.   }
  73.  }

  74.  /**
  75.   * 解压缩文件
  76.   *
  77.   * @param zis
  78.   * @param file
  79.   * @throws Exception
  80.   */
  81.  private static void fileUnZip(ZipInputStream zis, File file)
  82.    throws Exception {
  83.   ZipEntry zip = zis.getNextEntry();
  84.   if (zip == null)
  85.    return;
  86.   String name = zip.getName();
  87.   File f = new File(file.getAbsolutePath() + "/" + name);
  88.   if (zip.isDirectory()) {
  89.    f.mkdirs();
  90.    fileUnZip(zis, file);
  91.   } else {
  92.    f.createNewFile();
  93.    FileOutputStream fos = new FileOutputStream(f);
  94.    byte b[] = new byte[2048];
  95.    int aa = 0;
  96.    while ((aa = zis.read(b)) != -1) {
  97.     fos.write(b, 0, aa);
  98.    }
  99.    fos.close();
  100.    fileUnZip(zis, file);
  101.   }
  102.  }

  103.  /**
  104.   * 对directory目录下的文件压缩,保存为指定的文件zipFile
  105.   *
  106.   * @param directory
  107.   * @param zipFile
  108.   */
  109.  private static void zip(String directory, String zipFile) {
  110.   try {
  111.    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(
  112.      zipFile));
  113.    fileZip(zos, new File(directory));
  114.    zos.close();
  115.   } catch (Exception e) {
  116.    e.printStackTrace();
  117.   }
  118.  }

  119.  /**
  120.   * 解压缩文件zipFile保存在directory目录下
  121.   *
  122.   * @param directory
  123.   * @param zipFile
  124.   */
  125.  private static void unZip(String directory, String zipFile) {
  126.   try {
  127.    ZipInputStream zis = new ZipInputStream(
  128.      new FileInputStream(zipFile));
  129.    File f = new File(directory);
  130.    f.mkdirs();
  131.    fileUnZip(zis, f);
  132.    zis.close();
  133.   } catch (Exception e) {
  134.    e.printStackTrace();
  135.   }
  136.  }

  137.  /**
  138.   * 根据key的路径文件获得持久化成文件的key
  139.   * <P>
  140.   * 例子: RsaEncrypt.getKey("c:/systemkey/private.key");
  141.   *
  142.   * @param keyPath
  143.   * @return
  144.   */
  145.  public static Key getKey(String keyPath) throws Exception {
  146.   Key key = null;
  147.   FileInputStream fis = new FileInputStream(keyPath);
  148.   ObjectInputStream ofs = new ObjectInputStream(fis);
  149.   key = (Key) ofs.readObject();
  150.   return key;
  151.  }

  152.  /**
  153.   * 把文件srcFile加密后存储为destFile
  154.   *
  155.   * @param srcFile
  156.   * @param destFile
  157.   */
  158.  private static void encrypt(String srcFile, String destFile, Key privateKey)
  159.    throws Exception {
  160.   Cipher cipher = Cipher.getInstance("RSA");
  161.   cipher.init(Cipher.ENCRYPT_MODE, privateKey);
  162.   FileInputStream fis = new FileInputStream(srcFile);
  163.   FileOutputStream fos = new FileOutputStream(destFile);
  164.   byte[] b = new byte[53];
  165.   while (fis.read(b) != -1) {
  166.    fos.write(cipher.doFinal(b));
  167.   }
  168.   fos.close();
  169.   fis.close();
  170.  }

  171.  /**
  172.   * 把文件srcFile解密后存储为destFile
  173.   *
  174.   * @param srcFile
  175.   * @param destFile
  176.   * @param privateKey
  177.   * @throws Exception
  178.   */
  179.  private static void decrypt(String srcFile, String destFile, Key privateKey)
  180.    throws Exception {
  181.   Cipher cipher = Cipher.getInstance("RSA");
  182.   cipher.init(Cipher.DECRYPT_MODE, privateKey);
  183.   FileInputStream fis = new FileInputStream(srcFile);
  184.   FileOutputStream fos = new FileOutputStream(destFile);
  185.   byte[] b = new byte[64];
  186.   while (fis.read(b) != -1) {
  187.    fos.write(cipher.doFinal(b));
  188.   }
  189.   fos.close();
  190.   fis.close();
  191.  }

  192.  /**
  193.   * 对目录srcFile下的所有文件目录进行先压缩后操作,然后保存为destfile
  194.   *
  195.   * @param srcFile
  196.   *            要操作的目录 如c:/test/test
  197.   * @param destfile
  198.   *            压缩加密后存放的文件名 如c:/加密压缩文件.zip
  199.   * @param keyfile
  200.   *            公钥存放地点
  201.   */
  202.  public static void encryptZip(String srcFile, String destfile, String keyfile) throws Exception {
  203.   SecureRandom sr = new SecureRandom();
  204.   KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA");
  205.   kg.initialize(512, sr);
  206.   //产生新密钥对
  207.   KeyPair kp = kg.generateKeyPair();
  208.   //获得私匙
  209.   ZipEncrypt.privateKey = kp.getPrivate();
  210.   //获得公钥
  211.   ZipEncrypt.publicKey = kp.getPublic();
  212.   File f = new File(keyfile);
  213.   f.createNewFile();
  214.   FileOutputStream fos = new FileOutputStream(f);
  215.   ObjectOutputStream dos = new ObjectOutputStream(fos);
  216.   dos.writeObject(ZipEncrypt.publicKey);
  217.   
  218.   File temp = new File(UUID.randomUUID().toString() + ".zip");
  219.   temp.deleteOnExit();
  220.   // 先压缩文件
  221.   zip(srcFile, temp.getAbsolutePath());
  222.   // 对文件加密
  223.   encrypt(temp.getAbsolutePath(), destfile, privateKey);
  224.   temp.delete();
  225.  }

  226.  /**
  227.   * 对文件srcfile进行先解密后解压缩,然后解压缩到目录destfile下
  228.   *
  229.   * @param srcfile
  230.   *            要解密和解压缩的文件名 如c:/目标.zip
  231.   * @param destfile
  232.   *            解压缩后的目录 如c:/abc
  233.   * @param publicKey
  234.   *            公钥
  235.   */
  236.  public static void decryptUnzip(String srcfile, String destfile,
  237.    Key publicKey) throws Exception {
  238.   // 先对文件解密
  239.   File temp = new File(UUID.randomUUID().toString() + ".zip");
  240.   temp.deleteOnExit();
  241.   decrypt(srcfile, temp.getAbsolutePath(), publicKey);
  242.   // 解压缩
  243.   unZip(destfile, temp.getAbsolutePath());
  244.   temp.delete();
  245.  }

  246.  public static void main(String args[]) throws Exception { 
  247.   File f = new File(".");
  248.   Properties prop = new Properties(); ;
  249.   FileInputStream fis = new FileInputStream("./conf.properties");
  250.   prop.load(fis);
  251.   //要压缩的目录
  252.   String srcPath = prop.getProperty("SRC_PATH");
  253.   //压缩后的存放文件
  254.   String destZip = prop.getProperty("DEST_FILE");
  255.   //压缩加密后的publickey
  256.   String keyfile = prop.getProperty("KEY_FILE");
  257.   ZipEncrypt.encryptZip(srcPath, destZip,keyfile);
  258.   
  259.   /*解密
  260.   ZipEncrypt.decryptUnzip("e:/comXXX/comxxxx.zip", "d:/comxxx", ZipEncrypt
  261.     .getKey("e:/comXXX/public.key"));
  262.   */
  263.  }
  264. }
AES压缩加密/解压缩解密,网上一般用base64来对byte[]编码,其实不需要,指定AES/CBC/PKCS5Padding来指定加密解密时候位数不对的情况下,用pkcs5padding来附加位数,不过这个时候读解密的文件的时候,要多读16位的验证位就不会报异常
  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.ObjectInputStream;
  5. import java.security.Key;
  6. import java.security.SecureRandom;
  7. import java.util.UUID;
  8. import java.util.zip.ZipEntry;
  9. import java.util.zip.ZipInputStream;
  10. import java.util.zip.ZipOutputStream;

  11. import javax.crypto.Cipher;
  12. import javax.crypto.KeyGenerator;
  13. import javax.crypto.SecretKey;
  14. import javax.crypto.spec.IvParameterSpec;
  15. import javax.crypto.spec.SecretKeySpec;

  16. /**
  17.  * 对文件加密/解密和压缩/解压缩对象类
  18.  * @author 赵成明
  19.  */
  20. public class ZipEncrypt {
  21.         private  void directoryZip(ZipOutputStream out, File f, String base)
  22.                         throws Exception {
  23.                 // 如果传入的是目录
  24.             if (f.isDirectory()) {
  25.                 File[] fl = f.listFiles();
  26.                 // 创建压缩的子目录
  27.                 out.putNextEntry(new ZipEntry(base + "/"));
  28.                 if (base.length() == 0) {
  29.                     base = "";
  30.                 } else {
  31.                     base = base + "/";
  32.                 }
  33.                 for (int i = 0; i < fl.length; i++) {
  34.                     directoryZip(out, fl[i], base + fl[i].getName());
  35.                 }
  36.             } else {
  37.                     // 把压缩文件加入rar中
  38.                 out.putNextEntry(new ZipEntry(base));
  39.                 FileInputStream in = new FileInputStream(f);
  40.                 byte[] bb = new byte[2048];
  41.                 int aa = 0;
  42.                 while ((aa = in.read(bb)) != -1) {
  43.                         out.write(bb, 0, aa);
  44.                 }
  45.                 in.close();
  46.             }
  47.         }

  48.         /**
  49.          * 压缩文件
  50.          * @param zos
  51.          * @param file
  52.          * @throws Exception
  53.          */
  54.         private void fileZip(ZipOutputStream zos, File file)
  55.                         throws Exception {
  56.             if (file.isFile()) {
  57.                 zos.putNextEntry(new ZipEntry(file.getName()));
  58.                 FileInputStream fis = new FileInputStream(file);
  59.                 byte[] bb = new byte[2048];
  60.                 int aa = 0;
  61.                 while ((aa = fis.read(bb)) != -1) {
  62.                         zos.write(bb, 0, aa);
  63.                 }
  64.                 fis.close();
  65.                 System.out.println(file.getName());
  66.             } else {
  67.                 directoryZip(zos, file, "");
  68.             }
  69.         }

  70.         /**
  71.          * 解压缩文件
  72.          *
  73.          * @param zis
  74.          * @param file
  75.          * @throws Exception
  76.          */
  77.         private void fileUnZip(ZipInputStream zis, File file)
  78.                         throws Exception {
  79.             ZipEntry zip = zis.getNextEntry();
  80.             if (zip == null)
  81.                 return;
  82.             String name = zip.getName();
  83.             File f = new File(file.getAbsolutePath() + "/" + name);
  84.             if (zip.isDirectory()) {
  85.                 f.mkdirs();
  86.                 fileUnZip(zis, file);
  87.             } else {
  88.                 f.createNewFile();
  89.                 FileOutputStream fos = new FileOutputStream(f);
  90.                 byte b[] = new byte[2048];
  91.                 int aa = 0;
  92.                 while ((aa = zis.read(b)) != -1) {
  93.                     fos.write(b, 0, aa);
  94.                 }
  95.                 fos.close();
  96.                 fileUnZip(zis, file);
  97.             }
  98.         }

  99.         /**
  100.          * 对directory目录下的文件压缩,保存为指定的文件zipFile
  101.          *
  102.          * @param directory
  103.          * @param zipFile
  104.          */
  105.         private void zip(String directory, String zipFile) {
  106.             try {
  107.                 ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(
  108.                                 zipFile));
  109.                 fileZip(zos, new File(directory));
  110.                 zos.close();
  111.             } catch (Exception e) {
  112.                 e.printStackTrace();
  113.             }
  114.         }

  115.         /**
  116.          * 解压缩文件zipFile保存在directory目录下
  117.          *
  118.          * @param directory
  119.          * @param zipFile
  120.          */
  121.         private void unZip(String directory, String zipFile) {
  122.             try {
  123.                 ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
  124.                 File f = new File(directory);
  125.                 f.mkdirs();
  126.                 fileUnZip(zis, f);
  127.                 zis.close();
  128.             } catch (Exception e) {
  129.                 e.printStackTrace();
  130.             }
  131.         }

  132.         /**
  133.          * 根据key的路径文件获得持久化成文件的key
  134.          * <P>
  135.          * 例子: RsaEncrypt.getKey("c:/systemkey/private.key");
  136.          *
  137.          * @param keyPath
  138.          * @return
  139.          */
  140.         private Key getKey(String keyPath) throws Exception {
  141.             FileInputStream fis = new FileInputStream(keyPath);
  142.             byte[] b = new byte[16];
  143.             fis.read(b);
  144.             SecretKeySpec dks = new SecretKeySpec(b,"AES");
  145.             fis.close();
  146.             return dks;
  147.         }

  148.         /**
  149.          * 把文件srcFile加密后存储为destFile
  150.          *
  151.          * @param srcFile
  152.          * @param destFile
  153.          */
  154.         private void encrypt(String srcFile, String destFile, Key privateKey)
  155.                         throws Exception {
  156.          SecureRandom sr = new SecureRandom();
  157.             Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  158.             IvParameterSpec spec=new IvParameterSpec(privateKey.getEncoded());
  159.             cipher.init(Cipher.ENCRYPT_MODE, privateKey,spec,sr);
  160.             FileInputStream fis = new FileInputStream(srcFile);
  161.             FileOutputStream fos = new FileOutputStream(destFile);
  162.             byte[] b = new byte[2048];
  163.             while (fis.read(b) != -1) {
  164.                 fos.write(cipher.doFinal(b));
  165.             }
  166.             fos.close();
  167.             fis.close();
  168.         }

  169.         /**
  170.          * 把文件srcFile解密后存储为destFile
  171.          *
  172.          * @param srcFile
  173.          * @param destFile
  174.          * @param privateKey
  175.          * @throws Exception
  176.          */
  177.         private void decrypt(String srcFile, String destFile, Key privateKey)
  178.                         throws Exception {
  179.    SecureRandom sr = new SecureRandom();
  180.          Cipher ciphers = Cipher.getInstance("AES/CBC/PKCS5Padding");
  181.          IvParameterSpec spec=new IvParameterSpec(privateKey.getEncoded());
  182.          ciphers.init(Cipher.DECRYPT_MODE,privateKey,spec,sr);  
  183.             FileInputStream fis = new FileInputStream(srcFile);
  184.             FileOutputStream fos = new FileOutputStream(destFile); 
  185.             byte[] b = new byte[2064];
  186.             while (fis.read(b) != -1) {                 
  187.                 fos.write(ciphers.doFinal(b));
  188.             }
  189.             fos.close();
  190.             fis.close();
  191.         }

  192.         /**
  193.          * 对目录srcFile下的所有文件目录进行先压缩后操作,然后保存为destfile
  194.          *
  195.          * @param srcFile
  196.          *            要操作的目录 如c:/test/test
  197.          * @param destfile
  198.          *            压缩加密后存放的文件名 如c:/加密压缩文件.zip
  199.          * @param keyfile
  200.          *            公钥存放地点
  201.          */
  202.         public void encryptZip(String srcFile, String destfile, String keyfile) throws Exception {
  203.             SecureRandom sr = new SecureRandom();
  204.             KeyGenerator  kg = KeyGenerator.getInstance("AES");
  205.             kg.init(128,sr);
  206.             SecretKey key = kg.generateKey();
  207.             File f = new File(keyfile);
  208.             if (!f.getParentFile().exists())
  209.              f.getParentFile().mkdirs();
  210.             f.createNewFile();
  211.             FileOutputStream fos = new FileOutputStream(f);
  212.             fos.write(key.getEncoded());
  213.             File temp = new File(UUID.randomUUID().toString() + ".zip");
  214.             temp.deleteOnExit();
  215.             // 先压缩文件
  216.             zip(srcFile, temp.getAbsolutePath());
  217.             // 对文件加密
  218.             encrypt(temp.getAbsolutePath(), destfile, key);
  219.             temp.delete();
  220.         }

  221.         /**
  222.          * 对文件srcfile进行先解密后解压缩,然后解压缩到目录destfile下
  223.          *
  224.          * @param srcfile
  225.          *            要解密和解压缩的文件名 如c:/目标.zip
  226.          * @param destfile
  227.          *            解压缩后的目录 如c:/abc
  228.          * @param publicKey
  229.          *            公钥
  230.          */
  231.         public void decryptUnzip(String srcfile, String destfile,
  232.                         String keyfile) throws Exception {
  233.             // 先对文件解密
  234.             File temp = new File(UUID.randomUUID().toString() + ".zip");
  235.             temp.deleteOnExit();
  236.             decrypt(srcfile, temp.getAbsolutePath(), this.getKey(keyfile));
  237.             // 解压缩
  238.             unZip(destfile, temp.getAbsolutePath());
  239.             temp.delete();
  240.         }

  241.         public static void main(String args[]) throws Exception {
  242.       long a = System.currentTimeMillis();
  243.             new ZipEncrypt().encryptZip("e:/com""e:/comXXX/page.zip","e:/comXXX/public.key");
  244.            
  245.             System.out.println(System.currentTimeMillis()-a);
  246.             a = System.currentTimeMillis();
  247.            
  248.             new ZipEncrypt().decryptUnzip("e:/comXXX/page.zip""e:/comxxx""e:/comXXX/public.key");
  249.             System.out.println(System.currentTimeMillis()-a);
  250.         }
  251. }
加密:encryptZip
通过路径找到Key:getKey
解密:decryptUnzip

转自【http://topic.csdn.net/u/20081215/09/6ad763bd-a158-488a-8e5e-b34cec2a0424.html及http://www.blogjava.net/zhaochengming/archive/2007/09/03/142396.html】
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值