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

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

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

    suzixu

    BlogJava 首頁 新隨筆 聯系 聚合 管理
      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>標題: AESUtil</p>
     * <p>描述: AES加密工具類 實現對字符串(String)或文件的加密與解密 支持128、192、256位密匙</p>
     * <p>附: 若要使用192、256位密匙 需要到Sun下載jce_policy-6.zip 并解壓安裝</p>
     * 
    @author 見習和尚
     * 
    @version 1.0, 2010/09/10
     
    */

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

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

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

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

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

     
     
    /**
      * 構造方法
      
    */

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

     
     
    /**
      * 類入口方法,包含文件及字符串加解密調用示例
      * 
    @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位密匙(可由字母、數字、英文特殊字符組成):");
       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位密匙(可由字母、數字、英文特殊字符組成):");
       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{
      
      
    //校驗并創建文件目錄
      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{
      
    //校驗并創建文件目錄
      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(
    "字符串加密參數校驗失敗");
       
    return null;
      }

      
      
    //獲取KeyGenerator對象
      KeyGenerator kgen = KeyGenerator.getInstance("AES");
      
      
    //設置加密密匙位數,目前支持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(
    "字符串解密參數校驗失敗");
       
    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");
     }

     
     
    /**
      * 文件加密具體邏輯實現方法
      * 
      * 
    @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(
    "加密進度--->"+(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();
      }

     }


     
    /**
      * 文件解密具體邏輯實現方法
      * 
      * 
    @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(
    "解密進度--->"+(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();
      }

     }

     
     
    /**
      * 參數校驗
      * 
      * 
    @return boolean
      
    */

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

      
      
    return KEYSIZELIST.contains(keySize);
     }

     
     
    /**
      * 文件參數校驗,若不存在改文件目錄,則創建目錄;若該文件存在則刪除此文件
      * 
      * 
    @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 見習和尚 閱讀(6525) 評論(5)  編輯  收藏

    評論

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

    不過老兄的代碼太長了。

    看暈了。呵呵  回復  更多評論
      

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

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

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

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


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


    網站導航:
     
    主站蜘蛛池模板: 亚洲国产91精品无码专区| 男女超爽刺激视频免费播放| 亚洲国产成人精品不卡青青草原| 国产在线观看麻豆91精品免费| fc2免费人成在线| 亚洲AV无码AV男人的天堂不卡 | 亚洲日韩一区精品射精| 国产精品亚洲а∨无码播放| 啊灬啊灬别停啊灬用力啊免费看| 无码精品国产一区二区三区免费| 老司机精品视频免费| 久久乐国产综合亚洲精品| 亚洲国产韩国一区二区| 香蕉视频在线观看亚洲| 亚洲Av无码精品色午夜| 亚洲AV日韩AV高潮无码专区| 亚洲人成无码www久久久| 日本免费网站在线观看| 真实乱视频国产免费观看| 国产麻豆视频免费观看| 青娱分类视频精品免费2| 曰批视频免费30分钟成人| 两个人的视频高清在线观看免费| 五月婷婷综合免费| 免费无码看av的网站| 免费a级毛片18以上观看精品| 亚洲性日韩精品一区二区三区| 亚洲人成影院在线观看| 国产亚洲视频在线播放| 久久九九亚洲精品| 亚洲国产熟亚洲女视频| 一区二区免费国产在线观看| 18禁在线无遮挡免费观看网站| 中文字幕人成无码免费视频| 免费A级毛片无码A| 亚洲精品在线播放视频| 国产精品免费αv视频| 嘿嘿嘿视频免费网站在线观看| 可以免费观看一级毛片黄a| 亚洲伊人久久大香线蕉苏妲己| 免费无毒a网站在线观看|