2010-03-24 117 views
16

如何使用net/http驗證ruby中https://processing.ukash.com/這樣的站點的證書?如何使用net/http驗證ruby中的SSL證書鏈

https = Net::HTTP.new('processing.ukash.com', 443) 
https.use_ssl = true 
https.verify_mode = OpenSSL::SSL::VERIFY_NONE 

工作到目前爲止,但我如何驗證它現在是正確的證書?我從firefox中保存了證書,但生成的.pem文件中有許多證書,而net/http似乎並不喜歡它。

回答

22

從我的代碼片段集合:

#!/usr/bin/env ruby 
# How to: 
# ======= 
# Use Ruby's net/https library, to verify a SSL certificate. 
# ========================================================== 
# - Without verification the following code will lead to: 
# warning: peer certificate won't be verified in this SSL session 
# 
# #------------------begin example----------------------------- 
# require 'net/http' 
# require 'net/https' 
# require 'uri' 
# 
# url = URI.parse 'https://myname:[email protected]/' 
# http = Net::HTTP.new(url.host, url.port) 
# http.use_ssl = (url.scheme == 'https') 
# request = Net::HTTP::Get.new(url.path) 
# request.basic_auth url.user, url.password 
# response = http.request(request) 
# #-------------------end example------------------------------ 
# 
# To verify the ssl cert cosider adapting the following. 
# Status: Untested 
# ======= 
# 
# References: 
# =========== 
# [1] http://mimori.org/%7Eh/tdiary/20080301.html#p03 
# [2] http://redcorundum.blogspot.com/2008/03/ssl-certificates-and-nethttps.html 
# 
require 'net/http' 
require 'net/https' 
require 'uri' 

RootCA = '/etc/ssl/certs' 

url = URI.parse 'https://myname:[email protected]/' 
http = Net::HTTP.new(url.host, url.port) 
http.use_ssl = (url.scheme == 'https') 
if (File.directory?(RootCA) && http.use_ssl?) 
    http.ca_path = RootCA 
    http.verify_mode = OpenSSL::SSL::VERIFY_PEER 
    http.verify_depth = 5 
else 
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE 
end 
request = Net::HTTP::Get.new(url.path) 
request.basic_auth url.user, url.password 
response = http.request(request) 

希望這有助於?

+0

我彷彿從你的代碼出現錯誤。也許PEBKAC。 – Thufir 2012-01-23 08:58:08

+1

你能指出錯誤的要點嗎? – Hedgehog 2012-01-24 04:50:42

+0

我問糊貼永遠,但不知道。無論如何,鏈接:http://pastebin.mozilla.org/1460391可能很容易成爲我。我還沒有真正考慮過它。 – Thufir 2012-01-24 11:04:56