@@ -49,40 +49,33 @@ internal object CertUtils {
49
49
fun applySslSettings (builder : OkHttpClient .Builder , settings : SSLSettings ) {
50
50
// Modified from ApiClient.applySslSettings in the client package.
51
51
try {
52
- var customManagers = false
53
- var trustManagers: Array <TrustManager >? = null
54
- var keyManagers: Array <KeyManager >? = null
55
- if (settings.caCertPath != null ) {
56
- val tempTrustManagers = certToTrustManager(settings.caCertPath)
57
- if (tempTrustManagers.isNotEmpty()) {
58
- trustManagers = tempTrustManagers
59
- customManagers = true
60
- }
61
- }
62
- if (settings.clientCertPath != null ) {
63
- val tempKeyManagers = certToKeyManager(
64
- settings.clientCertPath,
65
- settings.clientCertPassword
66
- )
67
- if (tempKeyManagers.isNotEmpty()) {
68
- keyManagers = tempKeyManagers
69
- customManagers = true
70
- }
71
- }
72
- if (! settings.validateSSL) {
73
- trustManagers = arrayOf(trustAll)
52
+ val trustManagers = mutableSetOf<TrustManager >()
53
+ val keyManagers = mutableSetOf<KeyManager >()
54
+ if (settings.validateSSL) {
55
+ // Custom SSL validation
56
+ settings.caCertPath?.let { trustManagers.addAll(certToTrustManager(it)) }
57
+ } else {
58
+ // Disable SSL validation
59
+ trustManagers.add(trustAll)
74
60
builder.hostnameVerifier { _, _ -> true }
75
61
}
76
- if (customManagers || ! settings.validateSSL) {
77
- val context = SSLContext .getInstance(" TLS" )
78
- context.init (keyManagers, trustManagers, SecureRandom ())
79
- if (trustManagers == null ) {
62
+ settings.clientCertPath?.let {
63
+ keyManagers.addAll(certToKeyManager(it, settings.clientCertPassword))
64
+ }
65
+ if (trustManagers.isNotEmpty() || keyManagers.isNotEmpty()) {
66
+ if (trustManagers.isEmpty()) {
80
67
// Fall back to system trust managers
81
- trustManagers = defaultSystemTrustManager()
68
+ trustManagers.addAll( defaultSystemTrustManager() )
82
69
}
70
+ val context = SSLContext .getInstance(" TLS" )
71
+ context.init (
72
+ keyManagers.toTypedArray(),
73
+ trustManagers.toTypedArray(),
74
+ SecureRandom ()
75
+ )
83
76
builder.sslSocketFactory(
84
77
context.socketFactory,
85
- trustManagers[ 0 ] as X509TrustManager
78
+ trustManagers.elementAt( 0 ) as X509TrustManager
86
79
)
87
80
}
88
81
} catch (e: Exception ) {
@@ -114,8 +107,9 @@ internal object CertUtils {
114
107
require(certPassword != null ) { " empty client certificate password" }
115
108
116
109
val keyStore = KeyStore .getInstance(" PKCS12" )
117
- val inputStream = FileInputStream (File (certPath))
118
- keyStore.load(inputStream, certPassword.toCharArray())
110
+ FileInputStream (File (certPath)).use {
111
+ keyStore.load(it, certPassword.toCharArray())
112
+ }
119
113
val keyManagerFactory =
120
114
KeyManagerFactory .getInstance(KeyManagerFactory .getDefaultAlgorithm())
121
115
keyManagerFactory.init (keyStore, certPassword.toCharArray())
0 commit comments