當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby OCSP模塊用法及代碼示例

本文簡要介紹ruby語言中 OpenSSL::OCSP模塊 的用法。

OpenSSL::OCSP 實現在線證書狀態協議請求和響應。

創建和發送 OCSP 請求需要一個主題證書,該證書在 authorityInfoAccess 擴展中包含一個 OCSP URL 和主題證書的頒發者證書。首先,加載頒發者和主題證書:

subject = OpenSSL::X509::Certificate.new subject_pem
issuer  = OpenSSL::X509::Certificate.new issuer_pem

要創建請求,我們需要為主題證書創建一個證書 ID,以便 CA 知道我們詢問的是哪個證書:

digest = OpenSSL::Digest.new('SHA1')
certificate_id =
  OpenSSL::OCSP::CertificateId.new subject, issuer, digest

然後創建一個請求並將證書 ID 添加到其中:

request = OpenSSL::OCSP::Request.new
request.add_certid certificate_id

向請求添加隨機數可以防止重放攻擊,但並非所有 CA 都會處理隨機數。

request.add_nonce

要將請求提交給 CA 進行驗證,我們需要從主題證書中提取 OCSP URI

ocsp_uris = subject.ocsp_uris

require 'uri'

ocsp_uri = URI ocsp_uris[0]

要提交請求,我們會將請求發布到 OCSP URI (根據 RFC 2560)。請注意,在此示例中,我們僅處理 HTTP 請求,不處理任何重定向,因此這不足以嚴重使用。

require 'net/http'

http_response =
  Net::HTTP.start ocsp_uri.hostname, ocsp.port do |http|
    http.post ocsp_uri.path, request.to_der,
              'content-type' => 'application/ocsp-request'
end

response = OpenSSL::OCSP::Response.new http_response.body
response_basic = response.basic

首先,我們檢查響應是否具有有效簽名。如果沒有有效的簽名,我們將無法信任它。如果您在此處遇到故障,則可能缺少係統證書存儲或可能缺少中間證書。

store = OpenSSL::X509::Store.new
store.set_default_paths

unless response_basic.verify [], store then
  raise 'response is not signed by a trusted certificate'
end

響應包含狀態信息(成功/失敗)。我們可以將狀態顯示為字符串:

puts response.status_string #=> successful

接下來我們需要知道響應的詳細信息來確定響應是否與我們的請求相匹配。首先我們檢查隨機數。同樣,並非所有 CA 都支持 nonce。返回值的含義見 Request#check_nonce

p request.check_nonce basic_response #=> value from -1 to 3

然後從基本響應中提取證書的狀態信息。

single_response = basic_response.find_response(certificate_id)

unless single_response
  raise 'basic_response does not have the status for the certificate'
end

然後檢查有效性。將來發布的狀態必須被拒絕。

unless single_response.check_validity
  raise 'this_update is in the future or next_update time has passed'
end

case single_response.cert_status
when OpenSSL::OCSP::V_CERTSTATUS_GOOD
  puts 'certificate is still valid'
when OpenSSL::OCSP::V_CERTSTATUS_REVOKED
  puts "certificate has been revoked at #{single_response.revocation_time}"
when OpenSSL::OCSP::V_CERTSTATUS_UNKNOWN
  puts 'responder doesn't know about the certificate'
end

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 OCSP模塊。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。