2015년 12월 3일 목요일

andorid <-> php AES256 en/decode

출처 : http://www.imcore.net/encrypt-decrypt-aes256-c-objective-ios-iphone-ipad-php-java-android-perl-javascript-python/

android AES256Util class

  1. public class AES256Util {
  2. public static byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
  3.  
  4. public static String AES_Encode(String str, String key) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
  5.  
  6. byte[] textBytes = str.getBytes("UTF-8");
  7. AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
  8. SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
  9. Cipher cipher = null;
  10. cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  11. cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
  12.  
  13. return Base64.encodeToString(cipher.doFinal(textBytes), 0);
  14. }
  15.  
  16. public static String AES_Decode(String str, String key) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
  17.  
  18. byte[] textBytes =Base64.decode(str,0);
  19. //byte[] textBytes = str.getBytes("UTF-8");
  20. AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
  21. SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
  22. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  23. cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
  24. return new String(cipher.doFinal(textBytes), "UTF-8");
  25. }
  26. }

php function
  1. $AES256KEY = "12345678123456781234567812345678";
  2.  
  3. function AES_Encode($plain_text) {
  4. global $AES256KEY;
  5. return base64_encode(openssl_encrypt($plain_text, "AES-256-CBC", $AES256KEY, true, str_repeat(chr(0), 16)));
  6.  
  7. }
  8.  
  9. function AES_Decode($base64_text) {
  10. global $AES256KEY;
  11. return openssl_decrypt(base64_decode($base64_text), "AES-256-CBC", $AES256KEY, true, str_repeat(chr(0), 16));
  12. }

webview 로 데이터 전달
  1. try {
  2. encoeText = Uri.encode(AES256Util.AES_Encode(palinText, aes256key));
  3. } catch (Exception e) {}
  4.  
  5. String postdata = "enText="+encodeText;
  6. webView.postUrl(URL, postdata.getBytes());

webview 로 전달된 데이터가 복호화가 안된다면 전달하는 값에 +가 포함되어 그럴수도 있더라... 그래서 Uri.encode() 로 전달했다.

댓글 1개:

  1. java 와 php 간의 암호화시에 유용하게 사용하였습니다. 감사합니다~

    답글삭제