티스토리 뷰
SSL Pinning 이다 뭐다 해서 http 통신 할 때 공개키를 비교를 해서 동작해야 할 경우가 있다.
통신해야하는 도메인에서 공개키를 가져오는 코드를 확인해보자.
private fun getHttpPublicKey() {
CoroutineScope(Dispatchers.IO).launch {
val hostname = "도메인 주소"
val factory = HttpsURLConnection.getDefaultSSLSocketFactory()
try {
val socket = factory.createSocket(hostname, 443) as SSLSocket
socket.startHandshake()
val certs = socket.session.peerCertificates
val cert = certs[0]
val pKey = cert.publicKey.encoded
// Compute SHA-256 hash
val digest = MessageDigest.getInstance("SHA-256")
val publicKeySHA256 = digest.digest(pKey)
// Convert hash to hex string
val hexString = StringBuilder()
for (b in publicKeySHA256) {
val hex = Integer.toHexString(0xff and b.toInt())
if (hex.length == 1) hexString.append('0')
hexString.append(hex)
}
val bytes = hexString.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
// Pinning 에 사용 되는 키
val base64Key = android.util.Base64.encodeToString(bytes, android.util.Base64.DEFAULT)
// 만료 날짜 정보
val x509Cer = cert as X509Certificate
val lastDate = x509Cer.notAfter
} catch (e: Exception) {
e.printStackTrace()
}
}
}
이렇게 가져온 공개키를 신뢰할 수 있는 공개키와 비교해서 MITM 공격을 피할 수 있다.
'Android Memo' 카테고리의 다른 글
Android Double Click 기능 구현 (2) | 2024.08.06 |
---|---|
검색어 하이라이트 처리 (0) | 2022.11.22 |
Installed Build Tools revision 31.0.0 is corrupted (0) | 2022.06.21 |
EditText Custom Background 지정 (0) | 2020.06.23 |
반복문으로 문자열을 합칠 때 생기는 Warning 관련... (0) | 2019.01.17 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Android Custom Dialog
- fontFamily
- Android 더블 클릭
- targetSdkVersion 31
- ViewPager
- glide
- String append
- buildToolsVersion 31.0.0
- startForegroundService
- 문자열
- FrameAnimation
- notification
- AnimationDrawable
- android o
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함