Android examples for java.security:AES
aes Encrypt Hex
import java.security.KeyFactory; import java.security.MessageDigest; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Locale; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import android.util.Base64; public class Main{ /**//from w w w.j av a 2s . co m * UTF-8 */ public static final String UTF_8 = "UTF-8"; public static String aesEncryptHex(String content, String key) throws Exception { if (StringUtils.isBlank(content) || StringUtils.isBlank(key)) { throw new Exception("illegal params."); } return bytesToHexString(aes(Cipher.ENCRYPT_MODE, content.getBytes(UTF_8), key.getBytes(UTF_8))); } public static String bytesToHexString(byte[] bytes) { if (bytes == null || bytes.length <= 0) { return null; } StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < bytes.length; ++i) { int v = bytes[i] & 0xff; String hv = Integer.toHexString(v); if (hv.length() < 2) { stringBuilder.append(0); } stringBuilder.append(hv); } return stringBuilder.toString(); } public static byte[] aes(int opmode, byte[] content, byte[] key) throws Exception { SecureRandom secureRandom = null; secureRandom = SecureRandom.getInstance("SHA1PRNG", "Crypto"); secureRandom.setSeed(key); KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, secureRandom); Cipher cipher = Cipher.getInstance("AES/ECB/ZeroBytePadding"); cipher.init(opmode, new SecretKeySpec(kgen.generateKey() .getEncoded(), "AES")); return cipher.doFinal(content); } }