Android(안드로이드) - AES256 암복호화(Encryption, Decryption)
① 안드로이드 프로젝트 개발 중 서버와 단말기 통신 간의 데이터 암호화 기능이 필요해서 작업 완료 후
AES256 예제 소스 파일을 하단에 공유합니다.
② Java 에서도 많이 사용하므로, 실습해 보시면 많은 도움이 될 것 같습니다.
Android(안드로이드) - AES256 Chiper 소스 코드
원본코드
- 패키지 작성 후 원하는 곳에 붙여넣기 하셔서 사용하시면 됩니다.
- 비밀키 부분은 원하는 값으로 변경하셔야 겠죠?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.InvalidAlgorithmParameterException; import java.security.spec.AlgorithmParameterSpec; import android.util.Base64; public class AES256Chiper { public static byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; public static String secretKey = "비밀키"; //AES256 암호화 public static String AES_Encode(String str) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { byte[] textBytes = str.getBytes("UTF-8"); AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes); SecretKeySpec newKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), "AES"); Cipher cipher = null; cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec); return Base64.encodeToString(cipher.doFinal(textBytes), 0); } //AES256 복호화 public static String AES_Decode(String str) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { byte[] textBytes =Base64.decode(str,0); //byte[] textBytes = str.getBytes("UTF-8"); AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes); SecretKeySpec newKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec); return new String(cipher.doFinal(textBytes), "UTF-8"); } } | cs |
실행코드
- 암호화, 복호화 메소드 호출 예제
1 2 3 | public static String secretKey = "비밀키"; AES256Chiper.AES_Encode("암호화 내용"); AES256Chiper.AES_Decode("복호화 내용"); | cs |
Android(안드로이드) - 실행 화면
Android(안드로이드) - 샘플 소스 코드 다운로드
Java 및 안드로이드 프로젝트에서 전부 사용 가능해요.
'모바일 > Android' 카테고리의 다른 글
[Android] 안드로이드 - APK 파일 디컴파일 및 리소스 추출 방법 (0) | 2017.10.28 |
---|---|
[Android] 안드로이드 - 웹뷰 대체 라이브러리(AdvancedWebView) 사용법 (0) | 2017.10.27 |