<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    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加密工具類 實(shí)現(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)教后性價(jià)比很好的緩沖區(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{
      
      
    //校驗(yàn)并創(chuàng)建文件目錄
      validateFile(this.desFile);
      
      
    //獲取隨機(jī)密匙
      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{
      
    //校驗(yàn)并創(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ù)校驗(yàn)失敗");
       
    return null;
      }

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

      
    //獲取密匙對象
      SecretKey skey = kgen.generateKey();
      
      
    //獲取隨機(jī)密匙
      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ù)校驗(yàn)失敗");
       
    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");
     }

     
     
    /**
      * 文件加密具體邏輯實(shí)現(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();
      }

     }


     
    /**
      * 文件解密具體邏輯實(shí)現(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ù)校驗(yàn)
      * 
      * 
    @return boolean
      
    */

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

      
      
    return KEYSIZELIST.contains(keySize);
     }

     
     
    /**
      * 文件參數(shù)校驗(yàn),若不存在改文件目錄,則創(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;
     }

    }


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

    評論

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

    不過老兄的代碼太長了。

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

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

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

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

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


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


    網(wǎng)站導(dǎo)航:
     
    主站蜘蛛池模板: 午夜a级成人免费毛片| 亚洲欧洲自拍拍偷精品 美利坚| 亚洲国产精品一区二区三区久久| 亚洲VA中文字幕无码一二三区| 亚洲粉嫩美白在线| 成av免费大片黄在线观看| 两性刺激生活片免费视频| 亚洲日韩在线中文字幕第一页| 亚洲视频一区二区在线观看| 国产精品亚洲专一区二区三区| 最近免费最新高清中文字幕韩国| 国产一区二区三区无码免费| 亚洲永久永久永久永久永久精品| 污污的视频在线免费观看| 久久久久久久91精品免费观看| 亚洲精品国自产拍在线观看| 国产成人精品日本亚洲专| 国产一级高青免费| 午夜小视频免费观看| 亚洲午夜精品一区二区| 成人a毛片免费视频观看| 免费无码黄十八禁网站在线观看| 亚洲成AV人在线播放无码 | 久久亚洲国产欧洲精品一| 亚洲人成网站在线在线观看| 久久青草免费91线频观看不卡 | 亚洲乱码一二三四区麻豆| 国产成人自产拍免费视频| 在线播放免费人成视频在线观看| 亚洲三级电影网站| eeuss影院免费92242部| 国产精品麻豆免费版| 激情五月亚洲色图| 免费看又黄又无码的网站| 国产成人麻豆亚洲综合无码精品 | 无码日韩精品一区二区三区免费| 亚洲A∨精品一区二区三区| 日韩亚洲不卡在线视频中文字幕在线观看| 日日麻批免费40分钟无码| 久久精品夜色噜噜亚洲A∨| 九九精品国产亚洲AV日韩|