標籤:結束 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加解密詳解