使用java对文件或文件夹进行压缩和加密

使用Java对文件或文件夹的压缩, 解压, 加密和解密.  加解密类型使用的是AES.

使用zip对文件或文件夹进行压缩, 解压缩:
  1. import java.io.File;     
  2. import java.io.FileInputStream;     
  3. import java.io.FileOutputStream;     
  4. import java.io.IOException;     
  5. import java.util.zip.ZipEntry;     
  6. import java.util.zip.ZipInputStream;     
  7. import java.util.zip.ZipOutputStream;     
  8.     
  9. /**   
  10.  * 对文件或文件夹进行压缩和解压   
  11.  *   
  12.  */    
  13. public class ZipUtil {     
  14.     /**得到当前系统的分隔符*/    
  15. //  private static String separator = System.getProperty("file.separator");      
  16.     
  17.     /**   
  18.      * 添加到压缩文件中   
  19.      * @param out   
  20.      * @param f   
  21.      * @param base   
  22.      * @throws Exception   
  23.      */    
  24.     private void directoryZip(ZipOutputStream out, File f, String base) throws Exception {     
  25.         // 如果传入的是目录      
  26.         if (f.isDirectory()) {     
  27.             File[] fl = f.listFiles();     
  28.             // 创建压缩的子目录      
  29.             out.putNextEntry(new ZipEntry(base + "/"));     
  30.             if (base.length() == 0) {     
  31.                 base = "";     
  32.             } else {     
  33.                 base = base + "/";     
  34.             }     
  35.             for (int i = 0; i < fl.length; i++) {     
  36.                 directoryZip(out, fl[i], base + fl[i].getName());     
  37.             }     
  38.         } else {     
  39.             // 把压缩文件加入rar中      
  40.             out.putNextEntry(new ZipEntry(base));     
  41.             FileInputStream in = new FileInputStream(f);     
  42.             byte[] bb = new byte[10240];     
  43.             int aa = 0;     
  44.             while ((aa = in.read(bb)) != -1) {     
  45.                 out.write(bb, 0, aa);     
  46.             }     
  47.             in.close();     
  48.         }     
  49.     }     
  50.     
  51.     /**   
  52.      * 压缩文件   
  53.      *    
  54.      * @param zos   
  55.      * @param file   
  56.      * @throws Exception   
  57.      */    
  58.     private void fileZip(ZipOutputStream zos, File file) throws Exception {     
  59.         if (file.isFile()) {     
  60.             zos.putNextEntry(new ZipEntry(file.getName()));     
  61.             FileInputStream fis = new FileInputStream(file);     
  62.             byte[] bb = new byte[10240];     
  63.             int aa = 0;     
  64.             while ((aa = fis.read(bb)) != -1) {     
  65.                 zos.write(bb, 0, aa);     
  66.             }     
  67.             fis.close();     
  68.             System.out.println(file.getName());     
  69.         } else {     
  70.             directoryZip(zos, file, "");     
  71.         }     
  72.     }     
  73.     
  74.     /**   
  75.      * 解压缩文件   
  76.      *    
  77.      * @param zis   
  78.      * @param file   
  79.      * @throws Exception   
  80.      */    
  81.     private void fileUnZip(ZipInputStream zis, File file) throws Exception {     
  82.         ZipEntry zip = zis.getNextEntry();     
  83.         if (zip == null)     
  84.             return;     
  85.         String name = zip.getName();     
  86.         File f = new File(file.getAbsolutePath() + "/" + name);     
  87.         if (zip.isDirectory()) {     
  88.             f.mkdirs();     
  89.             fileUnZip(zis, file);     
  90.         } else {     
  91.             f.createNewFile();     
  92.             FileOutputStream fos = new FileOutputStream(f);     
  93.             byte b[] = new byte[10240];     
  94.             int aa = 0;     
  95.             while ((aa = zis.read(b)) != -1) {     
  96.                 fos.write(b, 0, aa);     
  97.             }     
  98.             fos.close();     
  99.             fileUnZip(zis, file);     
  100.         }     
  101.     }     
  102.          
  103.     /**   
  104.      * 根据filePath创建相应的目录   
  105.      * @param filePath   
  106.      * @return   
  107.      * @throws IOException   
  108.      */    
  109.     private File mkdirFiles(String filePath) throws IOException{     
  110.         File file = new File(filePath);     
  111.         if(!file.getParentFile().exists()){     
  112.             file.getParentFile().mkdirs();     
  113.         }     
  114.         file.createNewFile();     
  115.              
  116.         return file;     
  117.     }     
  118.     
  119.     /**   
  120.      * 对zipBeforeFile目录下的文件压缩,保存为指定的文件zipAfterFile   
  121.      *    
  122.      * @param zipBeforeFile     压缩之前的文件   
  123.      * @param zipAfterFile      压缩之后的文件   
  124.      */    
  125.     public void zip(String zipBeforeFile, String zipAfterFile) {     
  126.         try {     
  127.                  
  128.             ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(mkdirFiles(zipAfterFile)));     
  129.             fileZip(zos, new File(zipBeforeFile));     
  130.             zos.close();     
  131.         } catch (Exception e) {     
  132.             e.printStackTrace();     
  133.         }     
  134.     }     
  135.     
  136.     /**   
  137.      * 解压缩文件unZipBeforeFile保存在unZipAfterFile目录下   
  138.      *    
  139.      * @param unZipBeforeFile       解压之前的文件   
  140.      * @param unZipAfterFile        解压之后的文件   
  141.      */    
  142.     public void unZip(String unZipBeforeFile, String unZipAfterFile) {     
  143.         try {     
  144.             ZipInputStream zis = new ZipInputStream(new FileInputStream(unZipBeforeFile));     
  145.             File f = new File(unZipAfterFile);     
  146.             f.mkdirs();     
  147.             fileUnZip(zis, f);     
  148.             zis.close();     
  149.         } catch (Exception e) {     
  150.             e.printStackTrace();     
  151.         }     
  152.     }     
  153. }    
import java.io.File;   
import java.io.FileInputStream;   
import java.io.FileOutputStream;   
import java.io.IOException;   
import java.util.zip.ZipEntry;   
import java.util.zip.ZipInputStream;   
import java.util.zip.ZipOutputStream;   
  
/**  
 * 对文件或文件夹进行压缩和解压  
 *  
 */  
public class ZipUtil {   
    /**得到当前系统的分隔符*/  
//  private static String separator = System.getProperty("file.separator");   
  
    /**  
     * 添加到压缩文件中  
     * @param out  
     * @param f  
     * @param base  
     * @throws Exception  
     */  
    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[10240];   
            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[10240];   
            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[10240];   
            int aa = 0;   
            while ((aa = zis.read(b)) != -1) {   
                fos.write(b, 0, aa);   
            }   
            fos.close();   
            fileUnZip(zis, file);   
        }   
    }   
       
    /**  
     * 根据filePath创建相应的目录  
     * @param filePath  
     * @return  
     * @throws IOException  
     */  
    private File mkdirFiles(String filePath) throws IOException{   
        File file = new File(filePath);   
        if(!file.getParentFile().exists()){   
            file.getParentFile().mkdirs();   
        }   
        file.createNewFile();   
           
        return file;   
    }   
  
    /**  
     * 对zipBeforeFile目录下的文件压缩,保存为指定的文件zipAfterFile  
     *   
     * @param zipBeforeFile     压缩之前的文件  
     * @param zipAfterFile      压缩之后的文件  
     */  
    public void zip(String zipBeforeFile, String zipAfterFile) {   
        try {   
               
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(mkdirFiles(zipAfterFile)));   
            fileZip(zos, new File(zipBeforeFile));   
            zos.close();   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   
  
    /**  
     * 解压缩文件unZipBeforeFile保存在unZipAfterFile目录下  
     *   
     * @param unZipBeforeFile       解压之前的文件  
     * @param unZipAfterFile        解压之后的文件  
     */  
    public void unZip(String unZipBeforeFile, String unZipAfterFile) {   
        try {   
            ZipInputStream zis = new ZipInputStream(new FileInputStream(unZipBeforeFile));   
            File f = new File(unZipAfterFile);   
            f.mkdirs();   
            fileUnZip(zis, f);   
            zis.close();   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   
}  


使用AES对文件的加解密:

  1. import java.io.File;     
  2. import java.io.FileInputStream;     
  3. import java.io.FileOutputStream;     
  4. import java.io.IOException;     
  5. import java.security.Key;     
  6. import java.security.SecureRandom;     
  7.     
  8. import javax.crypto.Cipher;     
  9. import javax.crypto.KeyGenerator;     
  10. import javax.crypto.SecretKey;     
  11. import javax.crypto.spec.SecretKeySpec;     
  12.     
  13. /**   
  14.  * 使用AES对文件进行加密和解密   
  15.  *   
  16.  */    
  17. public class CipherUtil {     
  18.     /**   
  19.      * 使用AES对文件进行加密和解密   
  20.      *    
  21.      */    
  22.     private static String type = "AES";     
  23.     
  24.     /**   
  25.      * 把文件srcFile加密后存储为destFile   
  26.      * @param srcFile     加密前的文件   
  27.      * @param destFile    加密后的文件   
  28.      * @param privateKey  密钥   
  29.      * @throws GeneralSecurityException   
  30.      * @throws IOException   
  31.      */    
  32.     public void encrypt(String srcFile, String destFile, String privateKey) throws GeneralSecurityException, IOException {     
  33.         Key key = getKey(privateKey);     
  34.         Cipher cipher = Cipher.getInstance(type + "/ECB/PKCS5Padding");     
  35.         cipher.init(Cipher.ENCRYPT_MODE, key);     
  36.     
  37.         FileInputStream fis = null;     
  38.         FileOutputStream fos = null;     
  39.         try {     
  40.             fis = new FileInputStream(srcFile);     
  41.             fos = new FileOutputStream(mkdirFiles(destFile));     
  42.     
  43.             crypt(fis, fos, cipher);     
  44.         } catch (FileNotFoundException e) {     
  45.             e.printStackTrace();     
  46.         } catch (IOException e) {     
  47.             e.printStackTrace();     
  48.         } finally {     
  49.             if (fis != null) {     
  50.                 fis.close();     
  51.             }     
  52.             if (fos != null) {     
  53.                 fos.close();     
  54.             }     
  55.         }     
  56.     }     
  57.     
  58.     /**   
  59.      * 把文件srcFile解密后存储为destFile   
  60.      * @param srcFile     解密前的文件   
  61.      * @param destFile    解密后的文件   
  62.      * @param privateKey  密钥   
  63.      * @throws GeneralSecurityException   
  64.      * @throws IOException   
  65.      */    
  66.     public void decrypt(String srcFile, String destFile, String privateKey) throws GeneralSecurityException, IOException {     
  67.         Key key = getKey(privateKey);     
  68.         Cipher cipher = Cipher.getInstance(type + "/ECB/PKCS5Padding");     
  69.         cipher.init(Cipher.DECRYPT_MODE, key);     
  70.     
  71.         FileInputStream fis = null;     
  72.         FileOutputStream fos = null;     
  73.         try {     
  74.             fis = new FileInputStream(srcFile);     
  75.             fos = new FileOutputStream(mkdirFiles(destFile));     
  76.     
  77.             crypt(fis, fos, cipher);     
  78.         } catch (FileNotFoundException e) {     
  79.             e.printStackTrace();     
  80.         } catch (IOException e) {     
  81.             e.printStackTrace();     
  82.         } finally {     
  83.             if (fis != null) {     
  84.                 fis.close();     
  85.             }     
  86.             if (fos != null) {     
  87.                 fos.close();     
  88.             }     
  89.         }     
  90.     }     
  91.     
  92.     /**   
  93.      * 根据filePath创建相应的目录   
  94.      * @param filePath      要创建的文件路经   
  95.      * @return  file        文件   
  96.      * @throws IOException   
  97.      */    
  98.     private File mkdirFiles(String filePath) throws IOException {     
  99.         File file = new File(filePath);     
  100.         if (!file.getParentFile().exists()) {     
  101.             file.getParentFile().mkdirs();     
  102.         }     
  103.         file.createNewFile();     
  104.     
  105.         return file;     
  106.     }     
  107.     
  108.     /**   
  109.      * 生成指定字符串的密钥   
  110.      * @param secret        要生成密钥的字符串   
  111.      * @return secretKey    生成后的密钥   
  112.      * @throws GeneralSecurityException   
  113.      */    
  114.     private static Key getKey(String secret) throws GeneralSecurityException {     
  115.         KeyGenerator kgen = KeyGenerator.getInstance(type);     
  116.         kgen.init(128new SecureRandom(secret.getBytes()));     
  117.         SecretKey secretKey = kgen.generateKey();     
  118.         return secretKey;     
  119.     }     
  120.     
  121.     /**   
  122.      * 加密解密流   
  123.      * @param in        加密解密前的流   
  124.      * @param out       加密解密后的流   
  125.      * @param cipher    加密解密   
  126.      * @throws IOException   
  127.      * @throws GeneralSecurityException   
  128.      */    
  129.     private static void crypt(InputStream in, OutputStream out, Cipher cipher) throws IOException, GeneralSecurityException {     
  130.         int blockSize = cipher.getBlockSize() * 1000;     
  131.         int outputSize = cipher.getOutputSize(blockSize);     
  132.     
  133.         byte[] inBytes = new byte[blockSize];     
  134.         byte[] outBytes = new byte[outputSize];     
  135.     
  136.         int inLength = 0;     
  137.         boolean more = true;     
  138.         while (more) {     
  139.             inLength = in.read(inBytes);     
  140.             if (inLength == blockSize) {     
  141.                 int outLength = cipher.update(inBytes, 0, blockSize, outBytes);     
  142.                 out.write(outBytes, 0, outLength);     
  143.             } else {     
  144.                 more = false;     
  145.             }     
  146.         }     
  147.         if (inLength > 0)     
  148.             outBytes = cipher.doFinal(inBytes, 0, inLength);     
  149.         else    
  150.             outBytes = cipher.doFinal();     
  151.         out.write(outBytes);     
  152.     }     
  153. }    
import java.io.File;   
import java.io.FileInputStream;   
import java.io.FileOutputStream;   
import java.io.IOException;   
import java.security.Key;   
import java.security.SecureRandom;   
  
import javax.crypto.Cipher;   
import javax.crypto.KeyGenerator;   
import javax.crypto.SecretKey;   
import javax.crypto.spec.SecretKeySpec;   
  
/**  
 * 使用AES对文件进行加密和解密  
 *  
 */  
public class CipherUtil {   
    /**  
     * 使用AES对文件进行加密和解密  
     *   
     */  
    private static String type = "AES";   
  
    /**  
     * 把文件srcFile加密后存储为destFile  
     * @param srcFile     加密前的文件  
     * @param destFile    加密后的文件  
     * @param privateKey  密钥  
     * @throws GeneralSecurityException  
     * @throws IOException  
     */  
    public void encrypt(String srcFile, String destFile, String privateKey) throws GeneralSecurityException, IOException {   
        Key key = getKey(privateKey);   
        Cipher cipher = Cipher.getInstance(type + "/ECB/PKCS5Padding");   
        cipher.init(Cipher.ENCRYPT_MODE, key);   
  
        FileInputStream fis = null;   
        FileOutputStream fos = null;   
        try {   
            fis = new FileInputStream(srcFile);   
            fos = new FileOutputStream(mkdirFiles(destFile));   
  
            crypt(fis, fos, cipher);   
        } catch (FileNotFoundException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        } finally {   
            if (fis != null) {   
                fis.close();   
            }   
            if (fos != null) {   
                fos.close();   
            }   
        }   
    }   
  
    /**  
     * 把文件srcFile解密后存储为destFile  
     * @param srcFile     解密前的文件  
     * @param destFile    解密后的文件  
     * @param privateKey  密钥  
     * @throws GeneralSecurityException  
     * @throws IOException  
     */  
    public void decrypt(String srcFile, String destFile, String privateKey) throws GeneralSecurityException, IOException {   
        Key key = getKey(privateKey);   
        Cipher cipher = Cipher.getInstance(type + "/ECB/PKCS5Padding");   
        cipher.init(Cipher.DECRYPT_MODE, key);   
  
        FileInputStream fis = null;   
        FileOutputStream fos = null;   
        try {   
            fis = new FileInputStream(srcFile);   
            fos = new FileOutputStream(mkdirFiles(destFile));   
  
            crypt(fis, fos, cipher);   
        } catch (FileNotFoundException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        } finally {   
            if (fis != null) {   
                fis.close();   
            }   
            if (fos != null) {   
                fos.close();   
            }   
        }   
    }   
  
    /**  
     * 根据filePath创建相应的目录  
     * @param filePath      要创建的文件路经  
     * @return  file        文件  
     * @throws IOException  
     */  
    private File mkdirFiles(String filePath) throws IOException {   
        File file = new File(filePath);   
        if (!file.getParentFile().exists()) {   
            file.getParentFile().mkdirs();   
        }   
        file.createNewFile();   
  
        return file;   
    }   
  
    /**  
     * 生成指定字符串的密钥  
     * @param secret        要生成密钥的字符串  
     * @return secretKey    生成后的密钥  
     * @throws GeneralSecurityException  
     */  
    private static Key getKey(String secret) throws GeneralSecurityException {   
        KeyGenerator kgen = KeyGenerator.getInstance(type);   
        kgen.init(128, new SecureRandom(secret.getBytes()));   
        SecretKey secretKey = kgen.generateKey();   
        return secretKey;   
    }   
  
    /**  
     * 加密解密流  
     * @param in        加密解密前的流  
     * @param out       加密解密后的流  
     * @param cipher    加密解密  
     * @throws IOException  
     * @throws GeneralSecurityException  
     */  
    private static void crypt(InputStream in, OutputStream out, Cipher cipher) throws IOException, GeneralSecurityException {   
        int blockSize = cipher.getBlockSize() * 1000;   
        int outputSize = cipher.getOutputSize(blockSize);   
  
        byte[] inBytes = new byte[blockSize];   
        byte[] outBytes = new byte[outputSize];   
  
        int inLength = 0;   
        boolean more = true;   
        while (more) {   
            inLength = in.read(inBytes);   
            if (inLength == blockSize) {   
                int outLength = cipher.update(inBytes, 0, blockSize, outBytes);   
                out.write(outBytes, 0, outLength);   
            } else {   
                more = false;   
            }   
        }   
        if (inLength > 0)   
            outBytes = cipher.doFinal(inBytes, 0, inLength);   
        else  
            outBytes = cipher.doFinal();   
        out.write(outBytes);   
    }   
}  

对文件或文件夹进行压缩解压加密解密:
  1. import java.io.File;     
  2. import java.util.UUID;     
  3.     
  4. public class ZipCipherUtil {     
  5.     /**   
  6.      * 对目录srcFile下的所有文件目录进行先压缩后加密,然后保存为destfile   
  7.      *    
  8.      * @param srcFile   
  9.      *            要操作的文件或文件夹   
  10.      * @param destfile   
  11.      *            压缩加密后存放的文件   
  12.      * @param keyfile   
  13.      *            密钥   
  14.      */    
  15.     public void encryptZip(String srcFile, String destfile, String keyStr) throws Exception {     
  16.         File temp = new File(UUID.randomUUID().toString() + ".zip");     
  17.         temp.deleteOnExit();     
  18.         // 先压缩文件      
  19.         new ZipUtil().zip(srcFile, temp.getAbsolutePath());     
  20.         // 对文件加密      
  21.         new CipherUtil().encrypt(temp.getAbsolutePath(), destfile, keyStr);     
  22.         temp.delete();     
  23.     }     
  24.     
  25.     /**   
  26.      * 对文件srcfile进行先解密后解压缩,然后解压缩到目录destfile下   
  27.      *    
  28.      * @param srcfile   
  29.      *            要解密和解压缩的文件名    
  30.      * @param destfile   
  31.      *            解压缩后的目录   
  32.      * @param publicKey   
  33.      *            密钥   
  34.      */    
  35.     public void decryptUnzip(String srcfile, String destfile, String keyStr) throws Exception {     
  36.         File temp = new File(UUID.randomUUID().toString() + ".zip");     
  37.         temp.deleteOnExit();     
  38.         // 先对文件解密      
  39.         new CipherUtil().decrypt(srcfile, temp.getAbsolutePath(), keyStr);     
  40.         // 解压缩      
  41.         new ZipUtil().unZip(temp.getAbsolutePath(),destfile);     
  42.         temp.delete();     
  43.     }     
  44.          
  45.     public static void main(String[] args) throws Exception {     
  46.         long l1 = System.currentTimeMillis();     
  47.              
  48.         //加密      
  49. //      new ZipCipherUtil().encryptZip("d:\\test\\111.jpg", "d:\\test\\photo.zip", "12345");      
  50.         //解密      
  51.         new ZipCipherUtil().decryptUnzip("d:\\test\\photo.zip""d:\\test\\111_1.jpg""12345");     
  52.              
  53.         long l2 = System.currentTimeMillis();     
  54.         System.out.println((l2 - l1) + "毫秒.");     
  55.         System.out.println(((l2 - l1) / 1000) + "秒.");     
  56.     }     
  57. }    
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值