Android examples for java.security:AES
encode by AES/CBC/PKCS7Padding or by AES/ECB/PKCS7Padding
import java.io.UnsupportedEncodingException; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import android.util.Base64; public class Main { public static String encode(String stringToEncode, String Key, String IV) throws NullPointerException { try {/* w w w . ja va2 s . co m*/ SecretKeySpec skeySpec = getKey(Key); byte[] clearText = stringToEncode.getBytes("utf-8"); Cipher cipher; if (null != IV) { IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes()); cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec); } else { cipher = Cipher.getInstance("AES/ECB/PKCS7Padding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); } String encrypedValue = Base64.encodeToString(cipher.doFinal(clearText), Base64.DEFAULT); return encrypedValue; } catch (Exception e) { e.printStackTrace(); } return ""; } private static SecretKeySpec getKey(String Key) throws UnsupportedEncodingException { int keyLength = 256; byte[] keyBytes = new byte[keyLength / 8]; Arrays.fill(keyBytes, (byte) 0x0); byte[] passwordBytes = Key.getBytes("UTF-8"); int length = passwordBytes.length < keyBytes.length ? passwordBytes.length : keyBytes.length; System.arraycopy(passwordBytes, 0, keyBytes, 0, length); SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); return key; } }