JAVA Aes加解密詳解

來源:互聯網
上載者:User

標籤:結束   print   產生   style   param   secure   tin   instance   rac   

上篇隨筆留了一個問題,兩種加密結果不一樣?

其實是內部實現方式不一樣,具體見注釋

 1  /** 2      * 提供密鑰和向量進行加密 3      * 4      * @param sSrc 5      * @param key 6      * @param iv 7      * @return 8      * @throws Exception 9      */10     public static String Encrypt(String sSrc, byte[] key, byte[] iv) throws Exception {11         SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");// 根據給定的位元組數組構造一個密鑰12         Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// "演算法/模式/補碼方式"13         IvParameterSpec _iv = new IvParameterSpec(iv);// 使用CBC模式,需要一個向量iv,可增加密碼編譯演算法的強度14         cipher.init(Cipher.ENCRYPT_MODE, skeySpec, _iv);//用密鑰和一組演算法參數初始化此 Cipher15         byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));//按單部分操作加密或解密資料,或者結束一個多部分操作。16         return Base64.encodeBase64String(encrypted);17     }
 1  /** 2      * 加密 3      * @param content 4      * @param keyBytes 5      * @param iv 6      * @return 7      * @throws Exception 8      */ 9     public String AES_CBC_Encrypt(byte[] content, byte[] keyBytes, byte[] iv) throws Exception{10         try{11             KeyGenerator keyGenerator= KeyGenerator.getInstance("AES");//返回產生指定演算法的秘密密鑰的 KeyGenerator 對象12             keyGenerator.init(128, new SecureRandom(keyBytes) );//使用使用者提供的隨機源初始化此金鑰產生器,使其具有確定的密鑰大小13             SecretKey key=keyGenerator.generateKey();// 產生一個密鑰。14             Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");15             cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));16             byte[] result=cipher.doFinal(content);17             return Base64.encodeBase64String(result);18         }catch (Exception e) {19             e.printStackTrace();20             throw e;21         }22     }

 

JAVA Aes加解密詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.