Как добавить сертификаты SSL в Mutual TLS -соединение OKTTP?JAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Как добавить сертификаты SSL в Mutual TLS -соединение OKTTP?

Сообщение Anonymous »

У меня уже есть файлы .pem и .Key, которые я не хочу устанавливать/импортировать его локально, просто скажите моему клиенту использовать их, возможно ли это? Это не самоописанный сертификат < /p>

в основном, в моем завитке я делаю что -то вроде этого: < /p>

curl --key mykey.key --cert mycert.pem https://someurl.com/my-endpoint
< /code>

Я проверил этот ответ < /p>

Как сделать https -запрос с сертификатом SSL в модернизации < /p>

Также это https://github.com/square/okhttp/blob/m ... trust.java (но не может иметь смысла, так как я не получаю объект, который мне нужен)

ok -cly />
val okHttpClient = OkHttpClient.Builder()
.sslSocketFactory(?, ?) //here I tried to call sslSocketFactory, trustManager following the example from the CustomTrust.java
.build()
< /code>

Есть идеи для решения? />https://square.github.io/okhttp/https/# ... зноprivate fun trustedCertificatesInputStream(): InputStream {
val comodoRsaCertificationAuthority = (""
+ "-----BEGIN CERTIFICATE-----\n" +
"-----END CERTIFICATE-----")
return Buffer()
.writeUtf8(comodoRsaCertificationAuthority)
.inputStream()
}

val loggingInterceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}

fun createClient() : OkHttpClient {

val trustManager: X509TrustManager
val sslSocketFactory: SSLSocketFactory
try {
trustManager = trustManagerForCertificates(trustedCertificatesInputStream())
val sslContext = SSLContext.getInstance("TLS")
sslContext.init(null, arrayOf(trustManager), null)
sslSocketFactory = sslContext.socketFactory

} catch (e: GeneralSecurityException) {
throw RuntimeException(e)
}
return OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory, trustManager)
.connectTimeout(45, TimeUnit.SECONDS)
.readTimeout(45, TimeUnit.SECONDS)
.protocols(listOf(Protocol.HTTP_1_1))
.addInterceptor(loggingInterceptor)
.build()
}

@Throws(GeneralSecurityException::class)
private fun trustManagerForCertificates(input: InputStream): X509TrustManager {
val certificateFactory: CertificateFactory = CertificateFactory.getInstance("X.509")
val certificates: Collection = certificateFactory.generateCertificates(input)
val password = "password".toCharArray() // Any password will work.
val keyStore = newEmptyKeyStore(password)

for ((index, certificate) in certificates.withIndex()) {
val certificateAlias = index.toString()
keyStore.setCertificateEntry(certificateAlias, certificate)
}
// Use it to build an X509 trust manager.
val keyManagerFactory: KeyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
keyManagerFactory.init(keyStore, password)

val trustManagerFactory: TrustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(keyStore)

val trustManagers: Array = trustManagerFactory.getTrustManagers()
return trustManagers[0]!! as X509TrustManager
}

@Throws(GeneralSecurityException::class)
private fun newEmptyKeyStore(password: CharArray): KeyStore {
return try {
val keyStore = KeyStore.getInstance(KeyStore.getDefaultType())
val inputStream: InputStream? = null // By convention, 'null' creates an empty key store.
keyStore.load(inputStream, password)
keyStore
} catch (e: IOException) {
throw AssertionError(e)
}

}
< /code>

И я получаю ошибку < /p>

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
< /code>

Поиск об ошибке кажется, что я должен установить SSL локально, что я должен избегать этого, так как я не могу установить его на сервере, есть ли способ, которым я могу заставить его работать?

Подробнее здесь: https://stackoverflow.com/questions/602 ... connection
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Jdk11 httpclient mutual tls
    Anonymous » » в форуме JAVA
    0 Ответы
    46 Просмотры
    Последнее сообщение Anonymous
  • Android App Client Mutual TLS с Java Server
    Anonymous » » в форуме JAVA
    0 Ответы
    5 Просмотры
    Последнее сообщение Anonymous
  • Android App Client Mutual TLS с Java Server
    Anonymous » » в форуме Android
    0 Ответы
    4 Просмотры
    Последнее сообщение Anonymous
  • Включите TLS 1.0, TLS 1.1, TLS 1.2... Asp.NET IIS 10.0.
    Anonymous » » в форуме C#
    0 Ответы
    113 Просмотры
    Последнее сообщение Anonymous
  • Как добавить самоопределенные сертификаты в сертификаты по умолчанию в httpsurlconnection
    Anonymous » » в форуме Android
    0 Ответы
    3 Просмотры
    Последнее сообщение Anonymous

Вернуться в «JAVA»