您的位置:首页 > 其它

对文件压缩加密,解密解压缩,对称加密,DES算法

2010-06-08 23:38 295 查看
 

from(http://hi.baidu.com/yezongbo/blog/item/f79b6000823a8c82e850cd16.html)

 

package koal.project.xdxx.ra.admin.util;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import com.koal.common.util.Base64;

public class ZipSecurityUtil {
public ZipSecurityUtil() {
   super();

}

private static File[] toFiles(File[] srcFiles) {
   ArrayList files = new ArrayList();
   for (int i = 0; i < srcFiles.length; i++) {
    File file = srcFiles[i];
    if (!file.exists()) {
     System.out
       .println("warnning:the file you want to

backup is missing="
         + file.getAbsolutePath());
     continue;
    }
    if (file.isDirectory()) {
     // 递归调用
     File[] dir = toFiles(file.listFiles());
     for (int j = 0; j < dir.length; j++) {
      File dirfile = dir[j];
      files.add(dirfile);
     }
    } else {
     files.add(file);
    }
   }
   File[] a = new File[files.size()];
   return (File[]) files.toArray(a);
}

private static File[] toFiles(String[] srcFiles) {
   File[] a = new File[srcFiles.length];
   for (int i = 0; i < srcFiles.length; i++) {
    a[i] = new File(srcFiles[i]);
   }
   return toFiles(a);
}

/**

* @param file
* @param preffixLen
*            根目录长度,为0时使用绝对路径保存
* @return
*/
public static String entryName(File file, int preffixLen) {
   String entryName = file.getPath();
   if (file.isDirectory())
    entryName = entryName.endsWith(File.separator) ? entryName
      : entryName + File.separator;
   entryName = entryName.replace(File.separatorChar, '/').substring(
     preffixLen);
   return entryName;
}

/**
* 压缩文件

* @param srcFiles:
*            要被压缩的文件名
* @param dstDir:
*            压缩后的文件名
* @param comment:
*            文件注释
* @param preffixLen:
*            根目录长度,为0时使用绝对路径保存,大于0时,会对文件的绝对路径前减去该

长度
*/

public static void zip(String[] strFiles, String dstFile, String comment,
    int preffixLen) throws IOException {
   if (strFiles.length == 0)
    return;
   File fileDst = new File(dstFile);
   File parentDir = fileDst.getParentFile();
   if (!parentDir.exists()) {
    parentDir.mkdirs();
   }
   if (fileDst.exists())
    fileDst.delete();
   fileDst.createNewFile();

   ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fileDst));
   zos.setMethod(ZipOutputStream.DEFLATED);

   if (comment != null) {
    zos.setComment(comment);
   }

   DataOutputStream dos = new DataOutputStream(zos);

   File[] srcFiles = toFiles(strFiles);

   for (int i = 0; i < srcFiles.length; i++) {

    String entryPath = entryName(srcFiles[i], preffixLen);
    zos.putNextEntry(new ZipEntry(entryPath));

    FileInputStream fis = new FileInputStream(srcFiles[i]);

    byte[] buff = new byte[8192];
    int len = 0;

    while (true) {
     len = fis.read(buff);
     if (len == -1 || len == 0)
      break;

     dos.write(buff, 0, len);
    }

    zos.closeEntry();
    fis.close();
   }
   dos.close();
   zos.close();
}

/**
* 解压缩文件

* @param srcFile:
*            压缩文件名
* @param dstDir:
*            要解压到的目录
* @param entryName:
*            要解压哪个文件,如果为null则解压所有文件。
* @param retainPath:
*            是否保留文件路径信息,true-保留,false-不保留。
*/
public static void unzip(String srcFile, String dstDir, String entryName,
    boolean retainPath) throws Exception {

   ZipFile zipFile = null;

   try {
    zipFile = new ZipFile(srcFile);
    Enumeration entryEnu = zipFile.entries();
    while (entryEnu.hasMoreElements()) {
     File fileItem = null;
     ZipEntry entry = (ZipEntry) entryEnu.nextElement();

     String name = entry.getName();
     if (entryName != null && !entryName.equalsIgnoreCase(name))
      continue;
     if (dstDir != null) {
      if (!retainPath) {
       File f = new File(name);
       name = f.getName();
      } else {
       if (System.getProperty("os.name").indexOf

("Windows") != -1) {

        if (name.matches("^[a-zA-Z]:.*")) {
         // 如果是WINDOWS系统,将文件

名中的驱动器符号去掉
         name = name.substring

(name.indexOf('//') + 1);
        }
       }
      }
      fileItem = new File(dstDir + File.separator + name);
     } else {
      fileItem = new File(name);
     }

     File parentDir = fileItem.getParentFile();
     if (!parentDir.exists()) {
      parentDir.mkdirs();
     }
     if (fileItem.exists())
      fileItem.delete();
     fileItem.createNewFile();
     FileOutputStream fos = null;
     InputStream is = null;

     try {
      fos = new FileOutputStream(fileItem);
      is = zipFile.getInputStream(entry);

      byte[] buff = new byte[8192];
      int len = 0;
      while ((len = is.read(buff)) != -1) {
       fos.write(buff, 0, len);
      }
     } finally {
      try {
       fos.flush();
       fos.close();
       is.close();
      } catch (Exception e) {
      }
     }
    }
   } catch (Exception e) {
    throw new Exception("解压缩失败:" + e.getMessage());

   } finally {
    try {
     zipFile.close();
    } catch (Exception e) {
    }
   }

}

/**
* 将文件解压缩到指定的目录,保持被压缩文件的路径信息。
*/
public static void unzip(String zipFile, String dstDir) throws Exception {
   unzip(zipFile, dstDir, null, true);
}

/**
* 解压缩文件,覆盖被压缩的文件。
*/
public static void unzip(String zipFile) throws Exception {
   unzip(zipFile, null, null, true);
}

public static void zipEnc(String[] strFiles, String dstFile,
    String comment, int preffixLen, String password) throws Exception {

   File temp = new File(UUID.randomUUID().toString() + ".zip");
   temp.deleteOnExit();
   zip(strFiles, temp.getAbsolutePath(), comment, preffixLen);
   encrypt(temp.getAbsolutePath(), dstFile, password);
   temp.delete();
}

public static void unzipDec(String srcFile, String dstDir,
    String entryName, boolean retainPath, String pwd) throws Exception {
   File temp = new File(UUID.randomUUID().toString() + ".zip");
   temp.deleteOnExit();
   decrypt(srcFile, temp.getAbsolutePath(), pwd);
   unzip(temp.getAbsolutePath(), dstDir, entryName, retainPath);
   temp.delete();

}

public static byte[] padding(byte[] src){
   int length = src.length +src.length%8;
   byte[] rst = new byte[length];
   System.arraycopy(src, 0, rst, 0, src.length);
   return rst;
}

public static void decrypt(String srcFile, String destfile, String pwd)
    throws Exception {
   SecureRandom sr = new SecureRandom();
   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); 
   DESKeySpec dks = new DESKeySpec(padding(Base64.encode(pwd.getBytes()))); 
   SecretKey securekey = keyFactory.generateSecret(dks); 
  
   Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, securekey,sr);
        InputStream is = new FileInputStream(srcFile);
        OutputStream out = new FileOutputStream(destfile);
        CipherOutputStream cos = new CipherOutputStream(out, cipher);
        byte[] buffer = new byte[1024];
        
        byte[] pwdByte = new byte[20];
      int len = is.read(pwdByte);
        byte[] hashByte = DigisterUtil.getHashEncode(pwd.getBytes());
        
        if(len != 20 || hashByte.length!=20){
        throw new RuntimeException("密码错误");
        }
        for(int i= 0 ;i<20;i++){
        if(pwdByte[i] != hashByte[i]){
           throw new RuntimeException("密码错误");
        }
        }
        
        int r;
        while ( (r = is.read(buffer)) >= 0)
        {
            cos.write(buffer, 0, r);
        }
        cos.close();
        out.close();
        is.close();

}

 

public static void encrypt(String srcFile, String destfile, String pwd)
    throws Exception {
  
   SecureRandom sr = new SecureRandom();
   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); 
   DESKeySpec dks = new DESKeySpec(padding(Base64.encode(pwd.getBytes()))); 
   SecretKey securekey = keyFactory.generateSecret(dks); 
  
   Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, securekey,sr);
        InputStream is = new FileInputStream(srcFile);
        OutputStream out = new FileOutputStream(destfile);
        CipherInputStream cis = new CipherInputStream(is, cipher);
        byte[] buffer = new byte[1024];
        int r;
        out.write(DigisterUtil.getHashEncode(pwd.getBytes()));
        while ( (r = cis.read(buffer)) > 0)
        {
            out.write(buffer, 0, r);
        }
        cis.close();
        is.close();
        out.close();

}

public static void main(String[] args) throws Exception {
   String[] str = new String[] { "d:/test", };
//   zipEnc(str, "d:/test.zip", "", 0, "123");
//  
   unzipDec("D:/RABackup_2008-6-18-11-54-40.zip", null, null, true, "1223");
//   byte[] a =padding(Base64.encode("11".getBytes()));
//   System.out.println(a.length);
   // DesUtil des = new DesUtil("123");
   // byte[] bb = des.getEncByte("11111111".getBytes());
   // String str1 = new String(des.getDesByte(bb));
   // System.out.println(str1);
}

}

 

DigisterUtil.java类

package koal.project.xdxx.ra.admin.util;

import java.security.MessageDigest;

import com.koal.common.util.Base64;

public class DigisterUtil {

public static byte[] getHashEncode(byte[] str){
   try{
         MessageDigest sha = MessageDigest.getInstance("SHA");
             sha.update(Base64.encode(str));
         return sha.digest();
     } catch (Exception e){
         e.printStackTrace();
         throw new RuntimeException(e);
     }
}
}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息