Skip to content

Instantly share code, notes, and snippets.

@rogergcc
Created June 16, 2023 17:41
Show Gist options
  • Save rogergcc/038678210a6081e8887a618dfa7b6fd7 to your computer and use it in GitHub Desktop.
Save rogergcc/038678210a6081e8887a618dfa7b6fd7 to your computer and use it in GitHub Desktop.
not self signed
import android.util.Log
import java.security.KeyStore
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager
class MyTrustManagerPinned : X509TrustManager {
@Throws(CertificateException::class)
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
// No implementation needed
}
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
// Check if the certificate is self-signed
if (chain.isNullOrEmpty()) {
throw CertificateException("No se encontró el certificado del servidor")
}
if (chain.isNotEmpty() && chain[0].subjectDN == chain[0].issuerDN) {
Log.e("DEVLOG", "MyTrustManagerPinned checkServerTrusted error")
throw CertificateException("Self-signed certificates are not allowed")
}
// Check if the certificate is trusted by a CA
try {
val trustManager = getSystemDefaultTrustManager()
trustManager.checkServerTrusted(chain, authType)
} catch (e: CertificateException) {
Log.e(
"DEVLOG",
"MyTrustManagerPinned getSystemDefaultTrustManager error : " + e.message
)
throw CertificateException("Certificate is not trusted by a CA")
}
}
override fun getAcceptedIssuers(): Array<X509Certificate> {
return emptyArray()
}
private fun getSystemDefaultTrustManager(): X509TrustManager {
val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(null as KeyStore?)
val trustManagers = trustManagerFactory.trustManagers
return trustManagers[0] as X509TrustManager
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment