加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala:如何忽略’SSLHandshakeException’

发布时间:2020-12-16 09:55:08 所属栏目:安全 来源:网络整理
导读:有了这样的代码: val html = Source.fromURL("https://scans.io/json") 获得例外: Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.cert
有了这样的代码:

val html = Source.fromURL("https://scans.io/json")

获得例外:

Exception in thread "main" 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
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1886)
...

我可以找到如何修复Java但不知道 – 如何在Scala中修复它?

解决方法

您可以通过配置SSLContext来实现此目的.

这是一个有效的代码

import javax.net.ssl._
import java.security.cert.X509Certificate
import scala.io.Source

// Bypasses both client and server validation.
object TrustAll extends X509TrustManager {
  val getAcceptedIssuers = null

  def checkClientTrusted(x509Certificates: Array[X509Certificate],s: String) = {}

  def checkServerTrusted(x509Certificates: Array[X509Certificate],s: String) = {}
}

// Verifies all host names by simply returning true.
object VerifiesAllHostNames extends HostnameVerifier {
  def verify(s: String,sslSession: SSLSession) = true
}

// Main class
object Test extends App {
  // SSL Context initialization and configuration
  val sslContext = SSLContext.getInstance("SSL")
  sslContext.init(null,Array(TrustAll),new java.security.SecureRandom())
  HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory)
  HttpsURLConnection.setDefaultHostnameVerifier(VerifiesAllHostNames)

  // Actual call
  val html = Source.fromURL("https://scans.io/json")
  println(html.mkString)
}

这个怎么运作

Source.fromURL在场景后面使用java.net.HttpURLConnection.所以这段代码很简单,因为TrustAll会绕过checkClientTrusted和checkServerTrusted方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读