티스토리 뷰

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 공격을 피할 수 있다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/06   »
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
글 보관함