HelloWorld 善戰者,求之于勢,不責于人;故能擇人而任勢。

          知止而后有定,定而后能靜,靜而后能安,安而后能慮,慮而后能得。物有本末,事有終始。知所先后,則近道矣。

            BlogJava :: 首頁 ::  :: 聯系 ::  :: 管理 ::
            167 隨筆 :: 1 文章 :: 40 評論 :: 0 Trackbacks

          RSA壓縮加密/解壓縮解密
          import java.io.File;
          import java.io.FileInputStream;
          import java.io.FileOutputStream;
          import java.io.ObjectInputStream;
          import java.io.ObjectOutputStream;
          import java.security.Key;
          import java.security.KeyPair;
          import java.security.KeyPairGenerator;
          import java.security.PrivateKey;
          import java.security.PublicKey;
          import java.security.SecureRandom;
          import java.util.Properties;
          import java.util.UUID;
          import java.util.zip.ZipEntry;
          import java.util.zip.ZipInputStream;
          import java.util.zip.ZipOutputStream;

          import javax.crypto.Cipher;

          /**
           * 對文件壓縮加密/解密解壓縮 對象類
           *
           */
          public class ZipEncrypt {
           private static PrivateKey privateKey;
           private static PublicKey publicKey;
           private static 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[2048];
             int aa = 0;
             while ((aa = in.read(bb)) != -1) {
              out.write(bb, 0, aa);
             }
             in.close();
            }
           }

           /**
            * 壓縮文件
            * @param zos
            * @param file
            * @throws Exception
            */
           private static 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[2048];
             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 static 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[2048];
             int aa = 0;
             while ((aa = zis.read(b)) != -1) {
              fos.write(b, 0, aa);
             }
             fos.close();
             fileUnZip(zis, file);
            }
           }

           /**
            * 對directory目錄下的文件壓縮,保存為指定的文件zipFile
            *
            * @param directory
            * @param zipFile
            */
           private static void zip(String directory, String zipFile) {
            try {
             ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(
               zipFile));
             fileZip(zos, new File(directory));
             zos.close();
            } catch (Exception e) {
             e.printStackTrace();
            }
           }

           /**
            * 解壓縮文件zipFile保存在directory目錄下
            *
            * @param directory
            * @param zipFile
            */
           private static void unZip(String directory, String zipFile) {
            try {
             ZipInputStream zis = new ZipInputStream(
               new FileInputStream(zipFile));
             File f = new File(directory);
             f.mkdirs();
             fileUnZip(zis, f);
             zis.close();
            } catch (Exception e) {
             e.printStackTrace();
            }
           }

           /**
            * 根據key的路徑文件獲得持久化成文件的key
            * <P>
            * 例子: RsaEncrypt.getKey("c:/systemkey/private.key");
            *
            * @param keyPath
            * @return
            */
           public static Key getKey(String keyPath) throws Exception {
            Key key = null;
            FileInputStream fis = new FileInputStream(keyPath);
            ObjectInputStream ofs = new ObjectInputStream(fis);
            key = (Key) ofs.readObject();
            return key;
           }

           /**
            * 把文件srcFile加密后存儲為destFile
            *
            * @param srcFile
            * @param destFile
            */
           private static void encrypt(String srcFile, String destFile, Key privateKey)
             throws Exception {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(destFile);
            byte[] b = new byte[53];
            while (fis.read(b) != -1) {
             fos.write(cipher.doFinal(b));
            }
            fos.close();
            fis.close();
           }

           /**
            * 把文件srcFile解密后存儲為destFile
            *
            * @param srcFile
            * @param destFile
            * @param privateKey
            * @throws Exception
            */
           private static void decrypt(String srcFile, String destFile, Key privateKey)
             throws Exception {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(destFile);
            byte[] b = new byte[64];
            while (fis.read(b) != -1) {
             fos.write(cipher.doFinal(b));
            }
            fos.close();
            fis.close();
           }

           /**
            * 對目錄srcFile下的所有文件目錄進行先壓縮后操作,然后保存為destfile
            *
            * @param srcFile
            *            要操作的目錄 如c:/test/test
            * @param destfile
            *            壓縮加密后存放的文件名 如c:/加密壓縮文件.zip
            * @param keyfile
            *            公鑰存放地點
            */
           public static void encryptZip(String srcFile, String destfile, String keyfile) throws Exception {
            SecureRandom sr = new SecureRandom();
            KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA");
            kg.initialize(512, sr);
            //產生新密鑰對
            KeyPair kp = kg.generateKeyPair();
            //獲得私匙
            ZipEncrypt.privateKey = kp.getPrivate();
            //獲得公鑰
            ZipEncrypt.publicKey = kp.getPublic();
            File f = new File(keyfile);
            f.createNewFile();
            FileOutputStream fos = new FileOutputStream(f);
            ObjectOutputStream dos = new ObjectOutputStream(fos);
            dos.writeObject(ZipEncrypt.publicKey);
            
            File temp = new File(UUID.randomUUID().toString() + ".zip");
            temp.deleteOnExit();
            // 先壓縮文件
            zip(srcFile, temp.getAbsolutePath());
            // 對文件加密
            encrypt(temp.getAbsolutePath(), destfile, privateKey);
            temp.delete();
           }

           /**
            * 對文件srcfile進行先解密后解壓縮,然后解壓縮到目錄destfile下
            *
            * @param srcfile
            *            要解密和解壓縮的文件名 如c:/目標.zip
            * @param destfile
            *            解壓縮后的目錄 如c:/abc
            * @param publicKey
            *            公鑰
            */
           public static void decryptUnzip(String srcfile, String destfile,
             Key publicKey) throws Exception {
            // 先對文件解密
            File temp = new File(UUID.randomUUID().toString() + ".zip");
            temp.deleteOnExit();
            decrypt(srcfile, temp.getAbsolutePath(), publicKey);
            // 解壓縮
            unZip(destfile, temp.getAbsolutePath());
            temp.delete();
           }

           public static void main(String args[]) throws Exception { 
            File f = new File(".");
            Properties prop = new Properties(); ;
            FileInputStream fis = new FileInputStream("./conf.properties");
            prop.load(fis);
            //要壓縮的目錄
            String srcPath = prop.getProperty("SRC_PATH");
            //壓縮后的存放文件
            String destZip = prop.getProperty("DEST_FILE");
            //壓縮加密后的publickey
            String keyfile = prop.getProperty("KEY_FILE");
            ZipEncrypt.encryptZip(srcPath, destZip,keyfile);
            
            /*解密
            ZipEncrypt.decryptUnzip("e:/comXXX/comxxxx.zip", "d:/comxxx", ZipEncrypt
              .getKey("e:/comXXX/public.key"));
            */
           }
          }




           

           

          AES壓縮加密/解壓縮解密,網上一般用base64來對byte[]編碼,其實不需要,指定AES/CBC/PKCS5Padding
          來指定加密解密時候位數不對的情況下,用pkcs5padding來附加位數,不過這個時候讀解密的文件的時候,要多讀16位的驗證位就不會報異常

          import java.io.File;
          import java.io.FileInputStream;
          import java.io.FileOutputStream;
          import java.io.ObjectInputStream;
          import java.security.Key;
          import java.security.SecureRandom;
          import java.util.UUID;
          import java.util.zip.ZipEntry;
          import java.util.zip.ZipInputStream;
          import java.util.zip.ZipOutputStream;

          import javax.crypto.Cipher;
          import javax.crypto.KeyGenerator;
          import javax.crypto.SecretKey;
          import javax.crypto.spec.IvParameterSpec;
          import javax.crypto.spec.SecretKeySpec;

          /**
           * 對文件加密/解密和壓縮/解壓縮對象類
           * @author 趙成明
           */
          public class ZipEncrypt {
                  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[2048];
                          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[2048];
                          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[2048];
                          int aa = 0;
                          while ((aa = zis.read(b)) != -1) {
                              fos.write(b, 0, aa);
                          }
                          fos.close();
                          fileUnZip(zis, file);
                      }
                  }

                  /**
                   * 對directory目錄下的文件壓縮,保存為指定的文件zipFile
                   *
                   * @param directory
                   * @param zipFile
                   */
                  private void zip(String directory, String zipFile) {
                      try {
                          ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(
                                          zipFile));
                          fileZip(zos, new File(directory));
                          zos.close();
                      } catch (Exception e) {
                          e.printStackTrace();
                      }
                  }

                  /**
                   * 解壓縮文件zipFile保存在directory目錄下
                   *
                   * @param directory
                   * @param zipFile
                   */
                  private void unZip(String directory, String zipFile) {
                      try {
                          ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
                          File f = new File(directory);
                          f.mkdirs();
                          fileUnZip(zis, f);
                          zis.close();
                      } catch (Exception e) {
                          e.printStackTrace();
                      }
                  }

                  /**
                   * 根據key的路徑文件獲得持久化成文件的key
                   * <P>
                   * 例子: RsaEncrypt.getKey("c:/systemkey/private.key");
                   *
                   * @param keyPath
                   * @return
                   */
                  private Key getKey(String keyPath) throws Exception {
                      FileInputStream fis = new FileInputStream(keyPath);
                      byte[] b = new byte[16];
                      fis.read(b);
                      SecretKeySpec dks = new SecretKeySpec(b,"AES");
                      fis.close();
                      return dks;
                  }

                  /**
                   * 把文件srcFile加密后存儲為destFile
                   *
                   * @param srcFile
                   * @param destFile
                   */
                  private void encrypt(String srcFile, String destFile, Key privateKey)
                                  throws Exception {
                   SecureRandom sr = new SecureRandom();
                      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                      IvParameterSpec spec=new IvParameterSpec(privateKey.getEncoded());
                      cipher.init(Cipher.ENCRYPT_MODE, privateKey,spec,sr);
                      FileInputStream fis = new FileInputStream(srcFile);
                      FileOutputStream fos = new FileOutputStream(destFile);
                      byte[] b = new byte[2048];
                      while (fis.read(b) != -1) {
                          fos.write(cipher.doFinal(b));
                      }
                      fos.close();
                      fis.close();
                  }

                  /**
                   * 把文件srcFile解密后存儲為destFile
                   *
                   * @param srcFile
                   * @param destFile
                   * @param privateKey
                   * @throws Exception
                   */
                  private void decrypt(String srcFile, String destFile, Key privateKey)
                                  throws Exception {
             SecureRandom sr = new SecureRandom();
                   Cipher ciphers = Cipher.getInstance("AES/CBC/PKCS5Padding");
                   IvParameterSpec spec=new IvParameterSpec(privateKey.getEncoded());
                   ciphers.init(Cipher.DECRYPT_MODE,privateKey,spec,sr);  
                      FileInputStream fis = new FileInputStream(srcFile);
                      FileOutputStream fos = new FileOutputStream(destFile); 
                      byte[] b = new byte[2064];
                      while (fis.read(b) != -1) {                 
                          fos.write(ciphers.doFinal(b));
                      }
                      fos.close();
                      fis.close();
                  }

                  /**
                   * 對目錄srcFile下的所有文件目錄進行先壓縮后操作,然后保存為destfile
                   *
                   * @param srcFile
                   *            要操作的目錄 如c:/test/test
                   * @param destfile
                   *            壓縮加密后存放的文件名 如c:/加密壓縮文件.zip
                   * @param keyfile
                   *            公鑰存放地點
                   */
                  public void encryptZip(String srcFile, String destfile, String keyfile) throws Exception {
                      SecureRandom sr = new SecureRandom();
                      KeyGenerator  kg = KeyGenerator.getInstance("AES");
                      kg.init(128,sr);
                      SecretKey key = kg.generateKey();
                      File f = new File(keyfile);
                      if (!f.getParentFile().exists())
                       f.getParentFile().mkdirs();
                      f.createNewFile();
                      FileOutputStream fos = new FileOutputStream(f);
                      fos.write(key.getEncoded());
                      File temp = new File(UUID.randomUUID().toString() + ".zip");
                      temp.deleteOnExit();
                      // 先壓縮文件
                      zip(srcFile, temp.getAbsolutePath());
                      // 對文件加密
                      encrypt(temp.getAbsolutePath(), destfile, key);
                      temp.delete();
                  }

                  /**
                   * 對文件srcfile進行先解密后解壓縮,然后解壓縮到目錄destfile下
                   *
                   * @param srcfile
                   *            要解密和解壓縮的文件名 如c:/目標.zip
                   * @param destfile
                   *            解壓縮后的目錄 如c:/abc
                   * @param publicKey
                   *            公鑰
                   */
                  public void decryptUnzip(String srcfile, String destfile,
                                  String keyfile) throws Exception {
                      // 先對文件解密
                      File temp = new File(UUID.randomUUID().toString() + ".zip");
                      temp.deleteOnExit();
                      decrypt(srcfile, temp.getAbsolutePath(), this.getKey(keyfile));
                      // 解壓縮
                      unZip(destfile, temp.getAbsolutePath());
                      temp.delete();
                  }

                  public static void main(String args[]) throws Exception {
                long a = System.currentTimeMillis();
                      new ZipEncrypt().encryptZip("e:/com", "e:/comXXX/page.zip","e:/comXXX/public.key");
                     
                      System.out.println(System.currentTimeMillis()-a);
                      a = System.currentTimeMillis();
                     
                      new ZipEncrypt().decryptUnzip("e:/comXXX/page.zip", "e:/comxxx", "e:/comXXX/public.key");
                      System.out.println(System.currentTimeMillis()-a);
                  }
          }



          </script>

          posted on 2007-09-03 17:35 helloworld2008 閱讀(4648) 評論(2)  編輯  收藏 所屬分類: javajava - jca

          評論

          # re: 解密解壓縮的例子,DES/RSA 2008-04-28 08:39 xi
          123  回復  更多評論
            

          # re: 對文件壓縮加密/解密解壓縮的例子,DES/RSA[未登錄] 2008-12-21 20:47 what
          好像不是zip格式的,而其key是一個文件
          加密:encryptZip
          通過路徑找到Key:getKey
          解密:decryptUnzip   回復  更多評論
            

          主站蜘蛛池模板: 双江| 佛冈县| 平原县| 玉门市| 稻城县| 梧州市| 廉江市| 连州市| 那坡县| 桐柏县| 根河市| 吉林市| 皮山县| 桃源县| 天镇县| 沙坪坝区| 枝江市| 房产| 霸州市| 洛扎县| 昌平区| 彭泽县| 金沙县| 崇信县| 霸州市| 兴城市| 随州市| 桐柏县| 中牟县| 雷州市| 连城县| 洛阳市| 长春市| 葫芦岛市| 武邑县| 华亭县| 团风县| 嘉兴市| 扎赉特旗| 广河县| 义乌市|