Android examples for java.security:AES
aes Decrypt 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{ // w w w. ja v a2 s . c o m public static final String HEX_DIGITS = "0123456789ABCDEF"; /** * UTF-8 */ public static final String UTF_8 = "UTF-8"; public static String aesDecryptHex(String encryptHexStr, String key) throws Exception { if (StringUtils.isBlank(encryptHexStr) || StringUtils.isBlank(key)) { throw new Exception("illegal params."); } return new String(aes(Cipher.DECRYPT_MODE, hexStringToBytes(encryptHexStr), key.getBytes(UTF_8))); } 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); } public static byte[] hexStringToBytes(String hexString) { if (StringUtils.isBlank(hexString)) { return null; } char[] hexChars = hexString.toUpperCase(Locale.US).toCharArray(); int length = hexString.length() / 2; byte[] bytes = new byte[length]; for (int i = 0; i < length; ++i) { bytes[i] = (byte) (HEX_DIGITS.indexOf(hexChars[i * 2]) << 4 | HEX_DIGITS .indexOf(hexChars[i * 2 + 1])); } return bytes; } }