我的服务器使用的是 TLSv1.2 并且需要客户端证书才能连接。我可以使用 CURL 向服务器发送请求(这个请求工作正常):
curl --data "SAMPLETEXT" https://myserver.com/webservice --insecure --key privkey.pem --cert certificate.cert
(是的,服务器有自签名证书并且需要 --insecure
标志;不,我无法解决这个问题)。
现在,我想创建客户端以从 Scala 代码发送请求。 MyClient
是包含所需密码和路径的对象。为此,我创建了 SSLContext
:
private val keyStore = {
//Setting up BouncyCastle provider for message signing
Security.addProvider(new BouncyCastleProvider())
//Loading keystore from specified file
val clientStore = KeyStore.getInstance("JKS")
val inputStream = new FileInputStream(MyClient.keystore)
clientStore.load(inputStream, MyClient.keystorePassword.toCharArray)
inputStream.close()
clientStore
}
//Retrieving certificate and key
private val cert = keyStore.getCertificate(MyClient.keyAlias).asInstanceOf[X509Certificate]
private val key = keyStore.getKey(MyClient.keyAlias, MyClient.keystorePassword.toCharArray).asInstanceOf[PrivateKey]
//Creating SSL context
private val sslContext = {
val context = SSLContext.getInstance("TLS")
val tmf: TrustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm)
val kmf: KeyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm)
kmf.init(keyStore, MyClient.keystorePassword.toCharArray)
tmf.init(keyStore)
context.init(kmf.getKeyManagers, tmf.getTrustManagers, null)
context
}
然后用它来构建客户端:
private val httpClient =
richHttpBuilder(HttpEndpoint(baseUri))
.hostConnectionLimit(1)
.tlsWithoutValidation()
.tls(sslContext, Some(MyClient.host))
.build()
但我还是报错:
The future returned an exception of type: com.twitter.finagle.ChannelWriteException, with message: com.twitter.finagle.SslHandshakeException: General SSLEngine problem at remote address:
我做错了什么?
最佳答案
我花了一周时间才意识到我做错了什么。
选项 .tlsWithoutValidation()
和 .tls(sslContext, Some(MyClient.host))
不能同时使用,因为它们配置相同的属性(构建器的 Transport.TLSClientEngine
)。
共有三种解决方案。
使用正确的服务器证书。不幸的是,这个不适用。
将服务器证书添加到 keystore 。它将被标记为受信任,客户端将在没有
tlsWithoutValidation
的情况下愉快地工作。使用不验证任何内容的无知信任管理器:
private[this] class IgnorantTrustManager extends X509TrustManager { def getAcceptedIssuers(): Array[X509Certificate] = new Array[X509Certificate](0) def checkClientTrusted(certs: Array[X509Certificate], authType: String) { } def checkServerTrusted(certs: Array[X509Certificate], authType: String) { } }
然后将其用作信任管理器:
context.init(kmf.getKeyManagers, new IgnorantTrustManager(), null)
tlsWithoutValidation
选项必须被删除:richHttpBuilder(HttpEndpoint(baseUri)) .hostConnectionLimit(1) .tls(sslContext, Some(YandexClient.host)) .build()
此解决方案消除了证书的全部用途,因此它应该仅用于测试。
关于scala - 在 twitter finagle 中使用客户端证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30729704/