我想使用https协议连接到服务器。我有这个网站的自签名证书(.crt文件)。现在我想使用此证书连接到此网站。我目前正在使用客户端org.apache.http.impl.nio.client
,但如果证明它有用,我准备使用另一个客户端。
如果我有这个服务器的ssl证书,如何通过https连接到服务器?
答案 0 :(得分:1)
为了只允许应用程序中的特定证书,您必须遵循以下步骤:
为此,我打开了firefox,粘贴了我想要获取证书的网站地址。添加例外以下载此证书。然后,您可以通过单击地址栏右侧的绿色锁来访问它。屏幕截图将帮助您找到如何下载它。
请注意,您应该下载链证书,而不是网站的单一证书。在选择要导出的文件类型时,这是在ubuntu的文件浏览器中完成的。
使用刚刚下载的文件执行此命令:
keytool -import -file file_you_just_downloaded.crt -alias description_of_certificate -keystore
您现在拥有一个java密钥存储区,其中包含使用https连接到您网站的所有必需证书。
这些示例是使用apache nio Web客户端进行的。
import java.io.FileInputStream
import java.security.cert.X509Certificate
import java.security.{KeyStore, SecureRandom}
import javax.net.ssl._
import org.apache.http.conn.ssl.NoopHostnameVerifier
import org.apache.http.impl.nio.client.{CloseableHttpAsyncClient, HttpAsyncClients}
import org.apache.commons.io.IOUtils
import org.apache.http.ssl.SSLContexts
def httpClientFactory(
keyStoreFileName: String
): CloseableHttpAsyncClient = {
val httpClientBuilder = HttpAsyncClients.custom()
// activating or not the certificate checking
if (checkCertificate) {
// import keystore
val keyStorePassword = jksPassword // the password you used whit the command keytool
val ks = KeyStore.getInstance(KeyStore.getDefaultType)
val keyStorePath = getClass.getClassLoader.getResource(keyStoreFileName)
val inputStream = new FileInputStream(keyStorePath.getPath)
ks.load(inputStream, keyStorePassword.toArray)
IOUtils.closeQuietly(inputStream)
// create trust manager from keystore
val tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm)
tmf.init(ks)
val trustManager = tmf.getTrustManagers
// associate trust manager with the httpClient
val sslContext = SSLContext.getInstance("TLS")
sslContext.init(Array(), trustManager, null)
httpClientBuilder.setSSLContext(sslContext)
} else {
logger.warn("Warning ! Https connections will be done without checking certificate. Do not use in production.")
val sslContext = SSLContexts.createDefault()
sslContext.init(null, Array(new X509TrustManager {
override def getAcceptedIssuers: Array[X509Certificate] = Array.empty[X509Certificate]
override def checkClientTrusted(x509Certificates: Array[X509Certificate], s: String): Unit = {}
override def checkServerTrusted(x509Certificates: Array[X509Certificate], s: String): Unit = {}
}), new SecureRandom())
httpClientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setSSLContext(sslContext)
}
// ending httpClient creation
httpClientBuilder.build()
}
这里没有任何改变。