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

转:http://hao0610.iteye.com/blog/1181674

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


使用zip对文件或文件夹进行压缩, 解压缩:  
Java代码   收藏代码
  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. }  


使用AES对文件的加解密:  
Java代码   收藏代码
  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. }  


对文件或文件夹进行压缩解压加密解密:  
Java代码   收藏代码
  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.     }  

  1. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java文件压缩加密是一种将Java文件进行压缩加密保护的技术。通过对文件进行压缩,可以减小文件的体积,方便传输和存储。而通过加密文件,可以保护文件的内容,防止未经授权的人员获取和修改文件。 在Java中,可以使用压缩加密相关的类和方法来实现文件压缩加密操作。常用的压缩类有java.util.zip.ZipOutputStream和java.util.zip.ZipInputStream,通过这些类可以将文件文件夹压缩为zip格式的压缩包,或者解压缩已有的压缩包。 对于文件加密,可以使用Java提供的加密算法和密码库来实现。常用的加密算法有对称加密算法和非对称加密算法。对称加密算法如AES和DES可以使用相同的密钥进行加密解密,而非对称加密算法如RSA则需要一对公钥和私钥进行加密解密。通过在程序中使用对应的算法和密钥,可以将文件内容加密后保存,只有使用正确的密钥才能解密文件内容。 在实现文件压缩加密时,可以先将文件进行压缩,然后再对压缩后的文件进行加密操作。这样可以同时达到减小文件体积和保护文件内容的目的。在传输或存储文件时,可以先解密再解压缩,得到原始的文件内容。 总之,Java文件压缩加密是一种通过压缩加密的方式保护文件内容的技术,通过使用Java提供的压缩加密类、算法和密码库,可以方便地实现文件压缩加密操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值