【问题标题】:How do I validate the SSL certificate from an HTTPS connection, using a specific signing certificate?如何使用特定的签名证书从 HTTPS 连接验证 SSL 证书?
【发布时间】:2014-11-01 07:37:53
【问题描述】:

我正在更改一些 Ruby 代码以使用 https 方案,但我不喜欢将 SSL 验证策略设置为 VERFIY_NONE。 如何验证来自远程服务器的 SSL 证书是真实的?

【问题讨论】:

    标签: ruby ssl https x509


    【解决方案1】:

    假设您想从 HTTPS 服务器检索资源。

    许多人选择将 HTTP verify_mode 设置为 OPENSSL::SSL::VERIFY_NONE 以绕过任何 SSL 证书验证,但让 Ruby 验证 SSL 证书非常容易。

    注意有些人使用 OpenSSL::X509::Store#set_default_paths 来使用系统的默认可信证书。 如果这对你有用,很酷,但在我的情况下,受信任的签名证书不在系统存储中。我需要一个 使用内部生成的公共签名证书验证内部站点 SSL 证书的方法。

    您绝对需要的一件事是签署网站 SSL 证书的实体的公共证书。在我的 情况下,我有证书文件,但我需要将其从 DER X.509 证书(.cer 文件)转换为 Base-64 编码 X.509 证书,然后将 CER 扩展名重命名为 PEM。大多数平台(Windows、Linux、OSX 等)都有用于导入和导出证书的证书管理工具。这是必需的,因为 Ruby 似乎在本机使用 DER 证书方面存在问题。

    获得 PEM 文件后,我编写了以下代码

    url = URI.parse(https_url)
    http = Net::HTTP.new(url.host, url.port)
    if url.scheme == 'https'
      http.use_ssl = true
      # most people use VERIFY_NONE - change to force cert check
      http.verify_mode = OpenSSL::SSL::VERIFY_PEER
    
      #load the cert file
      cert  = Pathname.new(Dir.pwd) + "cert.pem"
      fail "no certificate file found" unless cert.exist?
      store = OpenSSL::X509::Store.new
      store.add_cert(OpenSSL::X509::Certificate.new(File.read(cert)))
      http.cert_store = store
    end
    
    # get the resource, validating the remote SSL cert first
    response = http.request(Net::HTTP::Get.new(url.request_uri))
    

    【讨论】:

      猜你喜欢
      • 2011-12-03
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 2014-01-26
      • 1970-01-01
      • 2012-12-31
      • 2017-04-18
      • 1970-01-01
      相关资源
      最近更新 更多