android AES 加密解密
阿新 • • 發佈:2018-12-30
import java.security.Provider; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * Created by free宇 2017/7/27. 11:44 * author:free宇 * email:[email protected] * describe: AES加密演算法*/ public class AesUtils { /** * @param * @return AES加密演算法加密 * @throws Exception */ public static String encrypt(String seed, String key) throws Exception { byte[] rawKey = getRawKey(key.getBytes()); byte[] result = encrypt(seed.getBytes("utf-8"), rawKey);return toHex(result); } public static byte[] encryptByte(String seed, String key) throws Exception { byte[] rawKey = getRawKey(key.getBytes()); return encrypt(seed.getBytes("utf-8"), rawKey); } public static String decryptString(byte[] byteData, byte[] byteKey) throwsException { byte[] rawKey = getRawKey(byteKey); byte[] result = decrypt(byteData, rawKey); return new String(result, "UTF8"); } /*** * AES加密演算法加密 * @param byteData 資料 * @param byteKey key * @return * @throws Exception */ private static byte[] encrypt(byte[] byteData, byte[] byteKey) throws Exception { return Ase(byteData, byteKey, Cipher.ENCRYPT_MODE); } /*** * AES加密演算法解密 * @param byteData 資料 * @param byteKey key * @return * @throws Exception */ private static byte[] decrypt(byte[] byteData, byte[] byteKey) throws Exception { return Ase(byteData, byteKey, Cipher.DECRYPT_MODE); } /*** * * @param byteData * @param byteKey * @param opmode * @return * @throws Exception */ private static byte[] Ase(byte[] byteData, byte[] byteKey, int opmode) throws Exception { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); SecretKeySpec skeySpec = new SecretKeySpec(byteKey, "AES"); cipher.init(opmode, skeySpec); byte[] decrypted = cipher.doFinal(byteData); return decrypted; } private static byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = null; int sdk_version = android.os.Build.VERSION.SDK_INT; if (sdk_version > 23) { // Android 6.0 以上 sr = SecureRandom.getInstance("SHA1PRNG", new CryptoProvider()); } else if (sdk_version >= 17) { sr = SecureRandom.getInstance("SHA1PRNG", "Crypto"); } else { sr = SecureRandom.getInstance("SHA1PRNG"); } sr.setSeed(seed); kgen.init(128, sr); // 192 and 256 bits may not be available SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); return raw; } public static class CryptoProvider extends Provider { /** * Creates a Provider and puts parameters */ public CryptoProvider() { super("Crypto", 1.0, "HARMONY (SHA1 digest; SecureRandom; SHA1withDSA signature)"); put("SecureRandom.SHA1PRNG", "org.apache.harmony.security.provider.crypto.SHA1PRNG_SecureRandomImpl"); put("SecureRandom.SHA1PRNG ImplementedIn", "Software"); } } private static String toHex(byte[] buf) { final String HEX = "0123456789ABCDEF"; if (buf == null) return ""; StringBuffer result = new StringBuffer(2 * buf.length); for (int i = 0; i < buf.length; i++) { result.append(HEX.charAt((buf[i] >> 4) & 0x0f)).append( HEX.charAt(buf[i] & 0x0f)); } return result.toString(); } private static byte[] toByte(String hexString) { int len = hexString.length() / 2; byte[] result = new byte[len]; for (int i = 0; i < len; i++) result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue(); return result; } }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; public class Base64 { private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" .toCharArray(); public static String encode(byte[] data) { int start = 0; int len = data.length; StringBuffer buf = new StringBuffer(data.length * 3 / 2); int end = len - 3; int i = start; int n = 0; while (i <= end) { int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 0x0ff) << 8) | (((int) data[i + 2]) & 0x0ff); buf.append(legalChars[(d >> 18) & 63]); buf.append(legalChars[(d >> 12) & 63]); buf.append(legalChars[(d >> 6) & 63]); buf.append(legalChars[d & 63]); i += 3; if (n++ >= 14) { n = 0; buf.append(" "); } } if (i == start + len - 2) { int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 255) << 8); buf.append(legalChars[(d >> 18) & 63]); buf.append(legalChars[(d >> 12) & 63]); buf.append(legalChars[(d >> 6) & 63]); buf.append("="); } else if (i == start + len - 1) { int d = (((int) data[i]) & 0x0ff) << 16; buf.append(legalChars[(d >> 18) & 63]); buf.append(legalChars[(d >> 12) & 63]); buf.append("=="); } return buf.toString(); } private static int decode(char c) { if (c >= 'A' && c <= 'Z') return ((int) c) - 65; else if (c >= 'a' && c <= 'z') return ((int) c) - 97 + 26; else if (c >= '0' && c <= '9') return ((int) c) - 48 + 26 + 26; else switch (c) { case '+': return 62; case '/': return 63; case '=': return 0; default: throw new RuntimeException("unexpected code: " + c); } } /** * Decodes the given Base64 encoded String to a new byte array. The byte * array holding the decoded data is returned. */ public static byte[] decode(String s) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { decode(s, bos); } catch (IOException e) { throw new RuntimeException(); } byte[] decodedBytes = bos.toByteArray(); try { bos.close(); bos = null; } catch (IOException ex) { System.err.println("Error while decoding BASE64: " + ex.toString()); } return decodedBytes; } private static void decode(String s, OutputStream os) throws IOException { int i = 0; int len = s.length(); while (true) { while (i < len && s.charAt(i) <= ' ') i++; if (i == len) break; int tri = (decode(s.charAt(i)) << 18) + (decode(s.charAt(i + 1)) << 12) + (decode(s.charAt(i + 2)) << 6) + (decode(s.charAt(i + 3))); os.write((tri >> 16) & 255); if (s.charAt(i + 2) == '=') break; os.write((tri >> 8) & 255); if (s.charAt(i + 3) == '=') break; os.write(tri & 255); i += 4; } } }View Code
也可以用android 自帶的base64工具類
android.util.Base64.encode(byteMi,android.util.Base64.DEFAULT); //編碼
android.util.Base64.decode(miData,android.util.Base64.DEFAULT); //解碼
專案要求介面普通介面用base64 重要介面用base64(aes(data,key)) 進行加密