# Android Java AES 加解密範例 ## 開發時遇到的問題 AES 設計時,應該確定好雙方的 **IV** 和 **Key** 值及值用的 **Mode 、Key Size 、 Output Base64** 或者 **HEX** ... 等問題。 雙方在做的時候,也能給個正確的範例。比方說,到此網頁試試 https://www.devglan.com/online-tools/aes-encryption-decryption ### AES 加密 Java 版(AES/CBC/HEX) ```java= //欲進行加密的文字字串 //Iv、Key 需看您的 Key Size 去設定長度,此範例是 128 //Key 最好的寫法是用「動態」,此方式為靜態,比較危險 private final static String IvAES = "kuochinghsiaokuo" ;//16字長度 private final static String KeyAES = "kuochinghsiaokuo";//16字長度 /** * AES加密 , 使用方式 AES.EncryptAES("pp@gmail.com") * @param text * @return 回傳 AES/CBC/HEX 字串 */ public static String EncryptAES(String text) { try { //轉成 Byte byte[] bb = text.getBytes(); byte[] iv = IvAES.getBytes("UTF-8"); byte[] key = KeyAES.getBytes("UTF-8"); AlgorithmParameterSpec mAlgorithmParameterSpec = new IvParameterSpec(iv); SecretKeySpec mSecretKeySpec = new SecretKeySpec(key, "AES"); Cipher mCipher = null; mCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); mCipher.init(Cipher.ENCRYPT_MODE, mSecretKeySpec, mAlgorithmParameterSpec); // byte 轉成 Hex String byte2HexStr = AES.parseByte2HexStr(mCipher.doFinal(bb)); return byte2HexStr; } catch(Exception ex) { return ""; } } // byte 轉成 Hex public static String parseByte2HexStr(byte buf[]) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } ``` ### AES 解密 Java 版(AES/CBC/HEX) ```java= /** * AES解密 , 使用方式 AES.DecryptAES("BB667399AD93E6771D4DB1852DC65953") * @param text * @return 回傳 加密前字串 */ public static String DecryptAES(String text) { try { // Hex 轉成 byte byte[] tobyte = AES.parseHexStr2Byte(text); byte[] iv = IvAES.getBytes("UTF-8"); byte[] key = KeyAES.getBytes("UTF-8"); AlgorithmParameterSpec mAlgorithmParameterSpec = new IvParameterSpec(iv); SecretKeySpec mSecretKeySpec = new SecretKeySpec(key, "AES"); Cipher mCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); mCipher.init(Cipher.DECRYPT_MODE, mSecretKeySpec, mAlgorithmParameterSpec); //轉成正常的字 String byte2string = new String(mCipher.doFinal(tobyte), StandardCharsets.UTF_8); return byte2string; } catch(Exception ex) { return ""; } } // Hex 轉成 byte public static byte[] parseHexStr2Byte(String hexString) { char[] hex = hexString.toCharArray(); int length = hex.length / 2; byte[] rawData = new byte[length]; for (int i = 0; i < length; i++) { int high = Character.digit(hex[i * 2], 16); int low = Character.digit(hex[i * 2 + 1], 16); int value = (high << 4) | low; if (value > 127) value -= 256; rawData [i] = (byte) value; } return rawData ; } ``` ## 雙方可提供的畫面 ![](https://i.imgur.com/X1D4Riv.png) ## 參考資料 待補 ###### tags: `Android` `Java` `AES` `CBC` `Hex` `Base64` `Encrypt` `Decrypt`