Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SerggioC/6986d55fe768d89bcc6ca38f10bded21 to your computer and use it in GitHub Desktop.
Save SerggioC/6986d55fe768d89bcc6ca38f10bded21 to your computer and use it in GitHub Desktop.
Load certificate from resources file
@Throws(
CertificateException::class,
KeyStoreException::class,
NoSuchAlgorithmException::class,
KeyManagementException::class
)
private fun getSSLConfig(context: Context): SSLContext {
val certificateFactory = CertificateFactory.getInstance("X.509")
context.resources.openRawResource(R.raw.tpv_certificate).use { inputStream ->
val ca: Certificate = certificateFactory.generateCertificate(inputStream)
// Creating a Keystore containing our trusted CAs
val keystoreType = KeyStore.getDefaultType()
val keyStore = KeyStore.getInstance(keystoreType)
keyStore.load(null, null)
keyStore.setCertificateEntry("ca", ca)
// Creating a TrustManager that trusts the CAs in our Keystore.
val tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm()
val tmf = TrustManagerFactory.getInstance(tmfAlgorithm)
tmf.init(keyStore)
// Creating an SSLSocketFactory that uses our TrustManager
val sslContext = SSLContext.getInstance("TLS")
sslContext.init(null, tmf.trustManagers, null)
return sslContext
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment