java学习

java学习

 

des对文件快速加解密

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kaishengit.util.desfile;

import com.google.gson.Gson;
import javax.crypto.KeyGenerator;
import javax.crypto.CipherInputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import java.security.SecureRandom;
import java.security.Key;
import java.io.*;
import java.security.*;
import java.util.ArrayList;
import java.util.List;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 *
 * @author Y-T测试成功
 */
public class DesFile3 {

    //  private static final String k = "24234";
    Key key;

    public DesFile3() {
        getKey("24234");//生成密匙
    }

    /**
     * 根据参数生成KEY
     */
    public void getKey(String strKey) {
        try {
            KeyGenerator _generator = KeyGenerator.getInstance("DES");
            _generator.init(new SecureRandom(strKey.getBytes()));
            this.key = _generator.generateKey();

            _generator = null;
        } catch (Exception e) {
            throw new RuntimeException("Error initializing SqlMap class. Cause: " + e);
        }
    }

    //加密以byte[]明文输入,byte[]密文输出   
    private byte[] getEncCode(byte[] byteS) {
        byte[] byteFina = null;
        Cipher cipher;
        try {
            cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byteFina = cipher.doFinal(byteS);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cipher = null;
        }

        return byteFina;
    }
    //  加密String明文输入,String密文输出 

    public String setEncString(String strMing) {
        BASE64Encoder base64en = new BASE64Encoder();
        String s = null;
        try {
            s = base64en.encode(getEncCode(strMing.getBytes("UTF8")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }

    public String setEncString(String strMing, int count) {
        BASE64Encoder base64en = new BASE64Encoder();
        String s = strMing;
        if (s != null) {
            for (int i = 0; i < count; i++) {
                try {
                    s = base64en.encode(getEncCode(s.getBytes("UTF8")));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            return s;
        }
        return s;
    }
    // 解密以byte[]密文输入,以byte[]明文输出   

    public byte[] getDesCode(byte[] byteD) {
        Cipher cipher;
        byte[] byteFina = null;
        try {
            cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byteFina = cipher.doFinal(byteD);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cipher = null;
        }
        return byteFina;
    }
    // 解密:以String密文输入,String明文输出  

    public String setDesString(String strMi) {
        BASE64Decoder base64De = new BASE64Decoder();
        String s = null;
        try {
            s = new String(getDesCode(base64De.decodeBuffer(strMi)), "UTF8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }

    public String setDesString(String strMi, int count) {
        BASE64Decoder base64De = new BASE64Decoder();
        String s = strMi;
        if (s != null) {
            for (int i = 0; i < count; i++) {
                try {
                    s = new String(getDesCode(base64De.decodeBuffer(s)), "UTF8");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            return s;
        }
        return s;
    }

    /**
     * 文件file进行加密并保存目标文件destFile中
     *
     * @param file 要加密的文件 如c:/test/srcFile.txt
     * @param destFile 加密后存放的文件名 如c:/加密后文件.txt
     */
    public void fileEncrypt(String file, String destFile) throws Exception {
        Cipher cipher = Cipher.getInstance("DES");
        // cipher.init(Cipher.ENCRYPT_MODE, getKey());
        cipher.init(Cipher.ENCRYPT_MODE, this.key);
        InputStream is = new FileInputStream(file);
        OutputStream out = new FileOutputStream(destFile);
        CipherInputStream cis = new CipherInputStream(is, cipher);
        byte[] buffer = new byte[1024];
        int r;
        while ((r = cis.read(buffer)) > 0) {
            out.write(buffer, 0, r);
        }
        cis.close();
        is.close();
        out.close();
    }

    public void fileEncrypt(String file, String destFile, int count) throws Exception {
        if(file!=null&&!"".equals(file)&&destFile!=null&&!"".equals(destFile)){
            if(count==1){
                    fileEncrypt( file,  destFile);
            }else {
                 String temp="";
         String st=file;
         for(int i=0;i<count;i++){
              if(i!=(count-1)){
                 temp="src/jia"+System.currentTimeMillis();
                  fileEncrypt( st,  temp);
           
                File f = new File(st);
                f.delete();
                st=temp;
           }else {
                  fileEncrypt( st,  destFile);
                  File f = new File(st);
                  f.delete();
           }
         }
            }
        }
   
    }

    /**
     * 文件采用DES算法解密文件
     *
     * @param file 已加密的文件 如c:/加密后文件.txt
     *         * @param destFile 解密后存放的文件名 如c:/ test/解密后文件.txt
     */
    public void fileDecrypt(String file, String dest) throws Exception {
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, this.key);
        InputStream is = new FileInputStream(file);
        OutputStream out = new FileOutputStream(dest);
        CipherOutputStream cos = new CipherOutputStream(out, cipher);
        byte[] buffer = new byte[1024];
        int r;
        while ((r = is.read(buffer)) >= 0) {
            cos.write(buffer, 0, r);
        }
        cos.close();
        out.close();
        is.close();
    }

    public void fileDecrypt(String file, String destFile, int count) throws Exception {

       if(file!=null&&!"".equals(file)&&destFile!=null&&!"".equals(destFile)){
            if(count==1){
                    fileDecrypt( file,  destFile);
            }else {
                 String temp="";
         String st=file;
         for(int i=0;i<count;i++){
              if(i!=(count-1)){
                 temp="src/jie"+System.currentTimeMillis();
                  fileDecrypt( st,  temp);
                  File f = new File(st);
                  f.delete();
                  st=temp;
           }else {
                  fileDecrypt( st,  destFile);
                  File f = new File(st);
                  f.delete();
           }
         }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        DesFile3 td = new DesFile3();
        long begin = System.currentTimeMillis();


        td.fileEncrypt("F:\\webservice\\webservice第一部分视频\\02_wsimport的使用.avi", "F:\\webservice\\webservice第一部分视频\\04",2); //加密
       
    long jia = System.currentTimeMillis();
   System.out.println((jia-begin)/1000);
     long begin1 = System.currentTimeMillis();
      //  td.fileDecrypt("F:\\webservice\\webservice第一部分视频\\04", "F:\\webservice\\webservice第一部分视频\\04.a"); //解密
           td.fileDecrypt("F:\\webservice\\webservice第一部分视频\\04", "F:\\webservice\\webservice第一部分视频\\04.avi",2); //解密
     long jie = System.currentTimeMillis();
      System.out.println((jie-begin1)/1000);
//        List<User> list = new ArrayList<User>();
//        User user = new User();
//        user.setId(1);
//        user.setAge(21);
//        user.setName("杨军威");
//        User user1 = new User();
//        user1.setId(2);
//        user1.setAge(23);
//        user1.setName("北京");
//        list.add(user);
//        list.add(user1);
//        Gson gson = new Gson();
//        String res = gson.toJson(list);
//        System.out.println(res);
//        System.out.println("加密==" + td.setEncString(res,2));
//        //  td.setEncString(res);
//        System.out.println("解密==" + td.setDesString(td.setEncString(res,2),2));
    }
}

posted on 2013-09-11 14:27 杨军威 阅读(394) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜