我想在Ruby中創建一個簡單的SSL客戶端和服務器。但是我收到了一條神祕的錯誤消息,文檔沒有任何幫助。試圖通過SSL創建一個簡單的Ruby服務器
這裏是我的服務器代碼:
#!/usr/bin/ruby
require "gserver"
require "openssl"
listeningPort = Integer(ARGV[0])
class Server < GServer
def initialize(listeningPort)
@sslContext = OpenSSL::SSL::SSLContext.new
@sslContext.cert = OpenSSL::X509::Certificate.new(File.open("MyCert.pem"))
super(listeningPort, "0.0.0.0")
end
def serve(io)
begin
ssl = OpenSSL::SSL::SSLSocket.new(io, @sslContext)
ssl.sync_close = true
ssl.connect
while (lineIn = ssl.gets)
lineIn = lineIn.chomp
$stdout.puts "=> " + lineIn
lineOut = "You said: " + lineIn
$stdout.puts "<= " + lineOut
ssl.puts lineOut
end
rescue
$stderr.puts $!
end
end
end
server = Server.new(listeningPort)
server.start
server.join
客戶端代碼是相似的:
#!/usr/bin/ruby
require "socket"
require "thread"
require "openssl"
host = ARGV[0]
port = Integer(ARGV[1])
socket = TCPSocket.new(host, port)
sslContext = OpenSSL::SSL::SSLContext.new
sslContext.cert = OpenSSL::X509::Certificate.new(File.open("MyCert.pem"))
ssl = OpenSSL::SSL::SSLSocket.new(socket, sslContext)
ssl.sync_close = true
ssl.connect
puts ssl.peer_cert # this is nil
Thread.new {
begin
while lineIn = ssl.gets
lineIn = lineIn.chomp
$stdout.puts lineIn
end
rescue
$stderr.puts "Error in input loop: " + $!
end
}
while (lineOut = $stdin.gets)
lineOut = lineOut.chomp
ssl.puts lineOut
end
當我連接,我得到的服務器和客戶端上此錯誤:
in `connect': SSL_connect returned=1 errno=0 state=SSLv2/v3 read server hello A: unknown protocol (OpenSSL::SSL::SSLError)
問題可能是它不信任證書(自簽名)。我不知道如何告訴客戶信任該證書。上面,我已經把服務器的證書放在了上下文中,但那只是黑暗中的一個鏡頭。我甚至不確定我的證書是否處於可接受的格式(它在base64中,證書和文件中的私鑰)。文檔非常少,網絡上也沒有太多這方面的內容。
任何想法?
啊,這有助於:http://stackoverflow.com/questions/4730544/ruby-openssl-documentation – Fantius 2011-05-03 18:00:24