suzixu

          BlogJava 首頁 新隨筆 聯(lián)系 聚合 管理
            4 Posts :: 0 Stories :: 5 Comments :: 0 Trackbacks

          AES加密,代碼如下:

          import java.security.InvalidKeyException;
          import java.util.ArrayList;
          import java.util.List;
          import java.util.Scanner;
          import javax.crypto.*;
          import javax.crypto.spec.*;
          import java.io.*;

          /**
           * <p>標(biāo)題: AESUtil</p>
           * <p>描述: AES加密工具類 實現(xiàn)對字符串(String)或文件的加密與解密 支持128、192、256位密匙</p>
           * <p>附: 若要使用192、256位密匙 需要到Sun下載jce_policy-6.zip 并解壓安裝</p>
           * 
          @author 見習(xí)和尚
           * 
          @version 1.0, 2010/09/10
           
          */

          public class AESTool {
           
          //密匙
           private byte[] key;
           
           
          //加密的密匙位數(shù)(默認(rèn)256位AES加密)
           private int keySize = 256;

           
          //待加密源文件
           private String srcFile;

           
          //加密后的文件
           private String desFile;

           
          //解密后的文件
           private String decodeFile;

           
          //調(diào)教后性價比很好的緩沖區(qū)大小(最好不要改動)
           private int blockSize = 61440;
           
           
          //有效密匙位數(shù)集合
           private static List<Integer> KEYSIZELIST = new ArrayList<Integer>();
           
           
          static{
            
          //初始化有效密匙位數(shù)
            KEYSIZELIST.add(128);
            KEYSIZELIST.add(
          192);
            KEYSIZELIST.add(
          256);
           }

           
           
          /**
            * 構(gòu)造方法
            
          */

           
          public AESTool(String srcFile,String desFile,String decodeFile,byte[] key){
            
          this.srcFile = srcFile;
            
          this.desFile = desFile;
            
          this.decodeFile = decodeFile;
            
          this.key = key;
           }

           
           
          /**
            * 類入口方法,包含文件及字符串加解密調(diào)用示例
            * 
          @param args
            * 
          @return void
            
          */

           
          public static void main(String[] args) throws Exception {
            System.out.println(
          "*******************************************");
            System.out.println(
          "***************AES加密工具*******************");
            System.out.println(
          "*********操作指令:1加密  2解密  3退出**********");
            System.out.println(
          "*******************************************");
            Scanner sc 
          = new Scanner(System.in);
            String commond 
          = null;
            
            
          do{
             System.out.println(
          "請輸入操作指令:");
             
          if(sc.hasNext()){
              commond 
          = sc.nextLine();
             }

            }
          while(!"1".equals(commond) && !"2".equals(commond) && !"3".equals(commond));
            
            
          if("1".equals(commond)){
             System.out.println(
          "請輸入原始文件路徑(如:c:/a.rar)");
             
             String srcFile 
          = null;
             
          if(sc.hasNext()){
              srcFile 
          = sc.nextLine();
             }

             
             System.out.println(
          "請輸入加密文件存放路徑(如:c:/b.uumap");
             String desFile 
          = null;
             
          if(sc.hasNext()){
              desFile 
          = sc.nextLine();
             }

             
             System.out.println(
          "請輸入32位密匙(可由字母、數(shù)字、英文特殊字符組成):");
             String key 
          = null;
             
          if(sc.hasNext()){
              key 
          = sc.nextLine();
             }

             
             sc.close();
             
             AESTool aesUtil 
          = new AESTool(srcFile,desFile,null,key.getBytes());

             aesUtil.encode();
          //文件加密
            }
          else if("2".equals(commond)){
             System.out.println(
          "請輸入加密文件存放路徑(如:c:/b.uumap");
             
             String desFile 
          = null;
             
          if(sc.hasNext()){
              desFile 
          = sc.nextLine();
             }

             
             System.out.println(
          "請輸入解密后文件存放路徑(如:c:/c.rar");
             String decodeFile 
          = null;
             
          if(sc.hasNext()){
              decodeFile 
          = sc.nextLine();
             }

             
             System.out.println(
          "請輸入32位密匙(可由字母、數(shù)字、英文特殊字符組成):");
             String key 
          = null;
             
          if(sc.hasNext()){
              key 
          = sc.nextLine();
             }

             
             sc.close();
             
             AESTool aesUtil 
          = new AESTool(null,desFile,decodeFile,key.getBytes());
             
             
          //文件加密解密示例
             aesUtil.decode();//文件解密*/
            }
          else if("3".equals(commond)){
             System.out.println(
          "******************退出**********************");
             System.exit(
          0);
            }

           }

           
           
          /**
            * 文件加密方法
            * 
          @return void
            * 
          @throws Exception
            
          */

           
          public void encode()throws Exception{
            
            
          //校驗并創(chuàng)建文件目錄
            validateFile(this.desFile);
            
            
          //獲取隨機密匙
            byte[] raw = this.key;

            
          //初始化SecretKeySpec對象
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

            
          //初始化Cipher對象
            Cipher cipher = Cipher.getInstance("AES");

            
          //用指定密匙對象初始化加密Cipher對象
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

            
          //加密文件
            encodeFile(cipher);
           }

           
           
          /**
            * 文件解密方法
            * 
          @return void
            * 
          @throws Exception
            
          */

           
          public void decode()throws Exception{
            
          //校驗并創(chuàng)建文件目錄
            validateFile(this.decodeFile);
            
            
          //初始化SecretKeySpec對象
            SecretKeySpec skeySpec = new SecretKeySpec(this.key, "AES");

            
          //初始化Cipher對象
            Cipher cipher = Cipher.getInstance("AES");

            
          //用指定密匙對象初始化加密Cipher對象
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

            
          //解密文件
            decodeFile(cipher,skeySpec);
           }

           
           
          /**
            * 字符串加密方法
            * 
          @return void
            * 
          @throws Exception
            
          */

           
          public byte[] encodeStr(String str,int keySize)throws Exception{
            
            
          if(!validate(str,keySize)){
             System.out.println(
          "字符串加密參數(shù)校驗失敗");
             
          return null;
            }

            
            
          //獲取KeyGenerator對象
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            
            
          //設(shè)置加密密匙位數(shù),目前支持128、192、256位
            kgen.init(keySize);

            
          //獲取密匙對象
            SecretKey skey = kgen.generateKey();
            
            
          //獲取隨機密匙
            byte[] raw = skey.getEncoded();

            
          //初始化SecretKeySpec對象
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

            
          //初始化Cipher對象
            Cipher cipher = Cipher.getInstance("AES");

            
          //用指定密匙對象初始化加密Cipher對象
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

            
          //加密字符串
            return cipher.doFinal(str.getBytes("utf-8"));
           }

           
           
          /**
            * 字符串解密方法
            * 
          @return void
            * 
          @throws Exception
            
          */

           
          public String decodeStr(byte[] date)throws Exception{

            
          if(null == date || date.length%16 !=0 ){
             System.out.println(
          "字符串解密參數(shù)校驗失敗");
             
          return null;
            }

            
            
          //初始化SecretKeySpec對象
            SecretKeySpec skeySpec = new SecretKeySpec(this.key, "AES");

            
          //初始化Cipher對象
            Cipher cipher = Cipher.getInstance("AES");

            
          //用指定密匙對象初始化加密Cipher對象
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            
            
          //解密字符串
            byte[] decData = cipher.doFinal(date);
            
            
          return new String(decData,"utf-8");
           }

           
           
          /**
            * 文件加密具體邏輯實現(xiàn)方法
            * 
            * 
          @param cipher
            * 
          @return void
            
          */

           
          public void encodeFile(Cipher cipher) {
            
            System.out.println(
          "**********啟動加密************");
            
            
          try {
             
          long readfilelen = 0;
                   BufferedRandomAccessFile brafReadFile;
                   BufferedRandomAccessFile brafWriteFile;
                   brafReadFile 
          = new BufferedRandomAccessFile(this.srcFile);
                   readfilelen 
          = brafReadFile.initfilelen;
                   brafWriteFile 
          = new BufferedRandomAccessFile(this.desFile, "rw"10);

                   
          byte buf[] = new byte[this.blockSize];
                   
          int readcount;

                   
          long start = System.currentTimeMillis();
                   
          double count = 0;
                   
          while((readcount = brafReadFile.read(buf)) != -1{
                    count
          +=readcount;
                    
          byte[] encData = cipher.doFinal(buf);
                       brafWriteFile.write(encData);
                       System.out.println(
          "加密進(jìn)度--->"+(int)((count/readfilelen)*100)+"%");
                   }


                   System.out.println(
          "BufferedRandomAccessFile Copy & Write File: "
                                      
          + brafReadFile.filename
                                      
          + "    FileSize: "
                                      
          + java.lang.Integer.toString((int)readfilelen >> 1024)
                                      
          + " (KB)    "
                                      
          + "Spend: "
                                      
          +(double)(System.currentTimeMillis()-start) / 1000
                                      
          + "(s)");
             
                   brafWriteFile.close();
                   brafReadFile.close();
             System.out.println(
          "**********加密完成************");
            }
           catch (FileNotFoundException e) {
             e.printStackTrace();
            }
          catch (IllegalBlockSizeException e) {
             e.printStackTrace();
            }
           catch (BadPaddingException e) {
             e.printStackTrace();
            }
          catch (IOException e) {
             e.printStackTrace();
            }

           }


           
          /**
            * 文件解密具體邏輯實現(xiàn)方法
            * 
            * 
          @param cipher
            * 
          @param skeySpec
            * 
          @return void
            
          */

           
          public void decodeFile(Cipher cipher,SecretKeySpec skeySpec){
            
            
          try {
             cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            }
           catch (InvalidKeyException e) {
             e.printStackTrace();
            }

            
            System.out.println(
          "**********啟動解密************");
            
            
          try {
             
          long readfilelen = 0;
                   BufferedRandomAccessFile brafReadFile;
                   BufferedRandomAccessFile brafWriteFile;
                   brafReadFile 
          = new BufferedRandomAccessFile(this.desFile);
                   readfilelen 
          = brafReadFile.initfilelen;
                   brafWriteFile 
          = new BufferedRandomAccessFile(this.decodeFile, "rw"10);

                   
          byte buf[] = new byte[this.blockSize+16];
                   
          int readcount;

                   
          long start = System.currentTimeMillis();
                   
          double count = 0;
                   
          while((readcount = brafReadFile.read(buf)) != -1{
                    count
          +=readcount;
                    
          byte[] decData = cipher.doFinal(buf);
                       brafWriteFile.write(decData);
                       System.out.println(
          "解密進(jìn)度--->"+(int)((count/readfilelen)*100)+"%");
                       
                   }


                   System.out.println(
          "BufferedRandomAccessFile Copy & Write File: "
                                      
          + brafReadFile.filename
                                      
          + "    FileSize: "
                                      
          + java.lang.Integer.toString((int)readfilelen >> 1024)
                                      
          + " (KB)    "
                                      
          + "Spend: "
                                      
          +(double)(System.currentTimeMillis()-start) / 1000
                                      
          + "(s)");
             
                   brafWriteFile.close();
                   brafReadFile.close();
             System.out.println(
          "**********解密完成************");
            }
           catch (FileNotFoundException e) {
             e.printStackTrace();
            }
          catch (IllegalBlockSizeException e) {
             e.printStackTrace();
            }
           catch (BadPaddingException e) {
             e.printStackTrace();
            }
          catch (IOException e) {
             e.printStackTrace();
            }

           }

           
           
          /**
            * 參數(shù)校驗
            * 
            * 
          @return boolean
            
          */

           
          private static boolean validate(String str, int keySize) {
            
            
          if(null==str){
             
          return false;
            }

            
            
          return KEYSIZELIST.contains(keySize);
           }

           
           
          /**
            * 文件參數(shù)校驗,若不存在改文件目錄,則創(chuàng)建目錄;若該文件存在則刪除此文件
            * 
            * 
          @return boolean
            
          */

           
          private static boolean validateFile(String filePath) {
            
            
          if(null==filePath || "".equals(filePath)){
             System.out.println(
          "無效的文件路徑");
             
          return false;
            }

            
            String dir 
          = filePath.substring(0, filePath.lastIndexOf("/")+1);
            
            File dirFile 
          = new File(dir);
            
            
          if(!dirFile.exists()){
             dirFile.mkdirs();
            }

            
            File file 
          = new File(filePath);
            
          if(file.exists()){
             file.delete();
            }

            
            
          return true;
           }

          }


          希望各位給點意見~~~
          posted on 2010-09-16 19:36 見習(xí)和尚 閱讀(6528) 評論(5)  編輯  收藏

          評論

          # re: 閑來無事,寫個AES(256位)加解密程序 2010-09-21 15:14 the_fire
          我很想給個意見,前天剛學(xué)了DES加密原理。

          不過老兄的代碼太長了。

          看暈了。呵呵  回復(fù)  更多評論
            

          # re: 閑來無事,寫個AES(256位)加解密程序 2012-04-06 00:11 en
          這個是使用系統(tǒng)的 AES .... 一般沒有 256位密鑰 的實現(xiàn)可用!!!  回復(fù)  更多評論
            

          # re: 閑來無事,寫個AES(256位)加解密程序[未登錄] 2012-04-06 09:11 見習(xí)和尚
          @en
          為什么要自己實現(xiàn)一個256位AES加密算法類?  回復(fù)  更多評論
            

          # re: 閑來無事,寫個AES(256位)加解密程序 2012-04-06 20:06 en
          @見習(xí)和尚
          當(dāng)程序跑在別人機器時候.沒辦法叫別人都有 AES256運行的權(quán)力.   回復(fù)  更多評論
            

          # re: 閑來無事,寫個AES(256位)加解密程序 2014-06-23 16:52 莫凡
          請問BufferRandomAccessFile那個類要怎么改啊@en
            回復(fù)  更多評論
            


          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 高淳县| 新余市| 白山市| 丹东市| 临安市| 大竹县| 台北市| 长春市| 邢台市| 夏河县| 清丰县| 庆城县| 莱西市| 城口县| 祁门县| 泾川县| 安国市| 呼和浩特市| 静海县| 连山| 佛山市| 阳谷县| 平罗县| 延川县| 康马县| 楚雄市| 华宁县| 嘉鱼县| 万宁市| 吉安县| 烟台市| 历史| 色达县| 穆棱市| 广南县| 开江县| 托克逊县| 崇州市| 喀喇| 枣庄市| 庐江县|