<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    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   回復  更多評論
      

    主站蜘蛛池模板: 中国亚洲呦女专区| 免费无码专区毛片高潮喷水| 国产成人A在线观看视频免费| 亚洲av无码一区二区三区四区| 中文字幕精品亚洲无线码一区 | 久久国产精品成人片免费| 亚洲一卡2卡3卡4卡国产网站| 国产公开免费人成视频| 国产在线观看免费视频软件| 亚洲综合久久一本伊伊区| 亚洲国产精品无码久久九九| 在线观看永久免费| 狼色精品人妻在线视频免费| 亚洲高清在线观看| 免费国产真实迷j在线观看| 99re在线免费视频| 视频一区在线免费观看| 内射少妇36P亚洲区| 四虎影视永久免费观看地址| 91成人在线免费视频| 深夜久久AAAAA级毛片免费看| 亚洲色图校园春色| 亚洲综合色在线观看亚洲| 91情侣在线精品国产免费| 青青操在线免费观看| 豆国产96在线|亚洲| 亚洲欧洲日产专区| 亚洲成AV人片在WWW色猫咪| 国产美女无遮挡免费视频 | 黄色免费网站网址| GOGOGO高清免费看韩国| 亚洲AV无码一区二区三区牲色| 亚洲av网址在线观看| 亚洲精品线路一在线观看| 永久免费无码网站在线观看| 99久久免费中文字幕精品| 香蕉免费看一区二区三区| 亚洲国产成人无码AV在线影院| 666精品国产精品亚洲| 亚洲日韩精品一区二区三区| 又爽又黄无遮挡高清免费视频|