使用Java对文件或文件夹的压缩, 解压, 加密和解密

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


使用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.     }  
  57. }  
》》》使用Java对文件加密和解密
package  com.copy.encrypt;
 
import  java.io.File;
import  java.io.FileInputStream;
import  java.io.FileNotFoundException;
import  java.io.FileOutputStream;
import  java.io.IOException;
import  java.io.InputStream;
import  java.io.OutputStream;
import  java.io.RandomAccessFile;
 
 
public  class  FileEncryptAndDecrypt {
     /**
      * 文件file进行加密
      * @param fileUrl 文件路径
      * @param key 密码
      * @throws Exception
      */
     public  static  void  encrypt(String fileUrl, String key) throws  Exception {
         File file = new  File(fileUrl);
         String path = file.getPath();
         if (!file.exists()){
             return ;
         }
         int  index = path.lastIndexOf( "\\" );
         String destFile = path.substring( 0 , index)+ "\\" + "abc" ;
         File dest = new  File(destFile);
         InputStream in = new  FileInputStream(fileUrl);
         OutputStream out = new  FileOutputStream(destFile);
         byte [] buffer = new  byte [ 1024 ];
         int  r;
         byte [] buffer2= new  byte [ 1024 ];
         while  (( r= in.read(buffer)) > 0 ) {
                 for ( int  i= 0 ;i<r;i++)
                 {
                     byte  b=buffer[i];
                     buffer2[i]=b== 255 ? 0 :++b;
                 }
                 out.write(buffer2, 0 , r);
                 out.flush();
         }
         in.close();
         out.close();
         file.delete();
         dest.renameTo( new  File(fileUrl));
         appendMethodA(fileUrl, key);
         System.out.println( "加密成功" );
     }
     
     /**
      *
      * @param fileName
      * @param content 密钥
      */
      public  static  void  appendMethodA(String fileName, String content) {
             try  {
                 // 打开一个随机访问文件流,按读写方式
                 RandomAccessFile randomFile = new  RandomAccessFile(fileName, "rw" );
                 // 文件长度,字节数
                 long  fileLength = randomFile.length();
                 //将写文件指针移到文件尾。
                 randomFile.seek(fileLength);
                 randomFile.writeBytes(content);
                 randomFile.close();
             } catch  (IOException e) {
                 e.printStackTrace();
             }
      }
      /**
       * 解密
       * @param fileUrl 源文件
       * @param tempUrl 临时文件
       * @param ketLength 密码长度
       * @return
       * @throws Exception
       */
      public  static  String decrypt(String fileUrl, String tempUrl, int  keyLength) throws  Exception{
             File file = new  File(fileUrl);
             if  (!file.exists()) {
                 return  null ;
             }
             File dest = new  File(tempUrl);
             if  (!dest.getParentFile().exists()) {
                 dest.getParentFile().mkdirs();
             }
             
             InputStream is = new  FileInputStream(fileUrl);
             OutputStream out = new  FileOutputStream(tempUrl);
             
             byte [] buffer = new  byte [ 1024 ];
             byte [] buffer2= new  byte [ 1024 ];
             byte  bMax=( byte ) 255 ;
             long  size = file.length() - keyLength;
             int  mod = ( int ) (size% 1024 );
             int  div = ( int ) (size>> 10 );
             int  count = mod== 0 ?div:(div+ 1 );
             int  k = 1 , r;
             while  ((k <= count && ( r = is.read(buffer)) > 0 )) {
                 if (mod != 0  && k==count) {
                     r =  mod;
                 }
                 
                 for ( int  i = 0 ;i < r;i++)
                 {
                     byte  b=buffer[i];
                     buffer2[i]=b== 0 ?bMax:--b;
                 }
                 out.write(buffer2, 0 , r);
                 k++;
             }
             out.close();
             is.close();
             return  tempUrl;
         }
      
      /**
       * 判断文件是否加密
       * @param fileName
       * @return
       */
      public  static  String readFileLastByte(String fileName, int  keyLength) {
          File file = new  File(fileName);
          if (!file.exists()) return  null ;
          StringBuffer str = new  StringBuffer();
             try  {
                 // 打开一个随机访问文件流,按读写方式
                 RandomAccessFile randomFile = new  RandomAccessFile(fileName, "r" );
                 // 文件长度,字节数
                 long  fileLength = randomFile.length();
                 //将写文件指针移到文件尾。
                 for ( int  i = keyLength ; i>= 1  ; i--){
                     randomFile.seek(fileLength-i);
                     str.append(( char )randomFile.read());
                 }
                 randomFile.close();
                 return  str.toString();
             } catch  (IOException e) {
                 e.printStackTrace();
             }
             return  null ;
          }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值