Guest User

Untitled

a guest
Mar 18th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.83 KB | None | 0 0
  1. object SslUtils {
  2.  
  3. fun getSslContextForCertificateFile(context: Context, fileName: String): SSLContext {
  4. try {
  5. val keyStore = SslUtils.getKeyStore(context, fileName)
  6. val sslContext = SSLContext.getInstance("SSL")
  7. val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
  8. trustManagerFactory.init(keyStore)
  9. sslContext.init(null, trustManagerFactory.trustManagers, SecureRandom())
  10. return sslContext
  11. } catch (e: Exception) {
  12. val msg = "Error during creating SslContext for certificate from assets"
  13. e.printStackTrace()
  14. throw RuntimeException(msg)
  15. }
  16. }
  17.  
  18. private fun getKeyStore(context: Context, fileName: String): KeyStore? {
  19. var keyStore: KeyStore? = null
  20. try {
  21. val assetManager = context.assets
  22. val cf = CertificateFactory.getInstance("X.509")
  23. val caInput = assetManager.open(fileName)
  24. val ca: Certificate
  25. try {
  26. ca = cf.generateCertificate(caInput)
  27. Log.d("SslUtilsAndroid", "ca=" + (ca as X509Certificate).subjectDN)
  28. } finally {
  29. caInput.close()
  30. }
  31.  
  32. val keyStoreType = KeyStore.getDefaultType()
  33. keyStore = KeyStore.getInstance(keyStoreType)
  34. keyStore!!.load(null, null)
  35. keyStore.setCertificateEntry("ca", ca)
  36. } catch (e: Exception) {
  37. e.printStackTrace()
  38. }
  39.  
  40. return keyStore
  41. }
  42.  
  43. fun getTrustAllHostsSSLSocketFactory(): SSLSocketFactory? {
  44. try {
  45. // Create a trust manager that does not validate certificate chains
  46. val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
  47.  
  48. override fun getAcceptedIssuers(): Array<X509Certificate> {
  49. return arrayOf()
  50. }
  51.  
  52. @Throws(CertificateException::class)
  53. override fun checkClientTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {
  54. }
  55.  
  56. @Throws(CertificateException::class)
  57. override fun checkServerTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {
  58. }
  59. })
  60.  
  61. // Install the all-trusting trust manager
  62. val sslContext = SSLContext.getInstance("SSL")
  63. sslContext.init(null, trustAllCerts, java.security.SecureRandom())
  64. // Create an ssl socket factory with our all-trusting manager
  65.  
  66. return sslContext.socketFactory
  67. } catch (e: KeyManagementException) {
  68. e.printStackTrace()
  69. return null
  70. } catch (e: NoSuchAlgorithmException) {
  71. e.printStackTrace()
  72. return null
  73. }
  74.  
  75. }
  76. }
Add Comment
Please, Sign In to add comment