1、ECB加密模式是最簡單的模式,每一個資料區塊之間沒有任何關係。因此它不需要也不能使用IV(初始化向量:Initialization vector)。預設的加密模式就是ECB(直接使用"AES"擷取演算法時) 2、其它加密模式需要使用IV,IV的使用方式: IvParameterSpec iv = new IvParameterSpec(keyBytes);
encypher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, alogorithmBase), iv); 注意進行加密時不指定初始化向量不會報錯,但是每次加密的結果都可能不同,不可預知。解密時必須制定初始化向量,否則會拋出異常。 3、沒有指定IV時,加密器會產生一個IV,產生演算法可能是隨機演算法。可以使用cliper.getIV()來擷取其產生的IV。再使用該IV進行解密就沒有問題了。通過更換IV也是演算法的一種安全保障。
import android.util.Base64;import java.security.Key;import javax.crypto.Cipher;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;public class EncryptUtil { /** * close * * @param content * @param key * @return */ public static String encrypt4AES(String content, String key) { try { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(initIv()); SecretKeySpec key1 = new SecretKeySpec(key.getBytes(), "AES"); cipher.init(Cipher.ENCRYPT_MODE, key1, iv); byte[] encryptedData = cipher.doFinal(content.getBytes()); String encryptResultStr = Base64.encodeToString(encryptedData, Base64.NO_WRAP);//不換行 return encryptResultStr; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 位移量.保證每次產生密文的唯一性 * * @return */ private static byte[] initIv() { String iv = "0000000000000000"; return iv.getBytes(); } /** * @param content * @param pass * @return open */ public static String deCiphering(String content, String pass) { byte[] bytea = Base64.decode(content, Base64.NO_WRAP); IvParameterSpec iv = new IvParameterSpec(initIv()); Key key = new SecretKeySpec(pass.getBytes(), "AES"); Cipher cipher = null; try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key, iv); //與加密時不同MODE:Cipher.DECRYPT_MODE byte[] ret = cipher.doFinal(bytea); return new String(ret, "utf-8"); } catch (Exception e) { e.printStackTrace(); } return null; }}