Android examples for java.security:AES
AES encrypt String and return a string
//package com.java2s; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class Main { public static final String AES = "AES"; public static String CRYPT_KEY = "your key"; public static byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };/* w w w . ja va2 s . co m*/ public final static String encrypt(String data) { try { return byte2hex(encrypt(data.getBytes("utf-8"), CRYPT_KEY)); } catch (Exception e) { e.printStackTrace(); } return null; } public static byte[] encrypt(byte[] src, String key) throws Exception { //SecretKey seckey = geneKey(key); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), AES); IvParameterSpec ivspec = new IvParameterSpec(iv);// ????????????? (IV) // ????????? cipher ?? Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// ?????????????? // Cipher ?? cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);// ???????,???????,?? // cipher.update(src); return cipher.doFinal(src);// ?????? } public static String byte2hex(byte[] b) { String hs = ""; String stmp = ""; for (int n = 0; n < b.length; n++) { stmp = (java.lang.Integer.toHexString(b[n] & 0XFF)); if (stmp.length() == 1) hs = hs + "0" + stmp; else hs = hs + stmp; } return hs.toUpperCase(); } }