How to check if a certificate is revoked on Android?

  Kiến thức lập trình

I’ve an issue checking the revocation status of a certificate. I need to put clearTrafficPermitted to true to have the certificate validated, otherwise the result I get is javax.net.ssl.SSLHandshakeException: Certificate revocation check failed: Unable to determine revocation status due to network error. I leave below my current code to make this verification:

fun getRevocationCheckingTrustManager(): X509TrustManager {
    val validator = CertPathValidator.getInstance("PKIX")
    val certificateFactory = CertificateFactory.getInstance("X509")

    val defaultTrustManager = getDefaultTrustManager()
    return object : X509TrustManager by defaultTrustManager {
        override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
            require(!(chain.isNullOrEmpty())) { "Certificate is null or empty" }
            require(!(authType.isNullOrEmpty())) { "Authtype is null or empty" }
            if (!authType.equals("ECDHE_RSA", ignoreCase = true) &&
                !authType.equals("ECDHE_ECDSA", ignoreCase = true) &&
                !authType.equals("RSA", ignoreCase = true) &&
                !authType.equals("ECDSA", ignoreCase = true)
            ) throw CertificateException("Certificate is not trust")

            try {
                val certPath: CertPath = certificateFactory.generateCertPath(chain.toList())
                val caKeystore = KeyStore.getInstance("AndroidCAStore").also { it.load(null) }
                val params = PKIXBuilderParameters(caKeystore, X509CertSelector())

                params.addCertPathChecker(validator.revocationChecker as PKIXRevocationChecker)
                validator.validate(certPath, params) as PKIXCertPathValidatorResult
            } catch (e: CertPathValidatorException) {
                throw CertificateException("Certificate revocation check failed: ${e.message}")
            } catch (e: Exception) {
                throw CertificateException("Certificate generic error")
            }
        }
    }
}

Does anyone know how I can do this check without having to set the clearTrafficPermitted property to true?

Thanks in advance!

LEAVE A COMMENT