我在python上有这样的代码通过socket连接到某些软件:
import socket, ssl
host = '127.0.0.1'
port = 8963
sert_key = '../keys/key.pem'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True)
sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, True)
sock.settimeout(30.5)
sock.connect((host, port))
sock = ssl.wrap_socket(sock, server_side=True, certfile=sert_key,
ssl_version=ssl.PROTOCOL_TLSv1)
cert = "hello"
cert = cert.encode('utf-8')
req = ('%08x'%len(cert))+cert
sock.sendall(req)
print sock.recv(4096)
输出:“OK”,所以它的工作。
我尝试在ruby上转换这样的代码,但它不起作用:
require 'socket'
require 'openssl'
host = '127.0.0.1'
port = 8963
sert_key = '../keys/key.pem'
socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
address = Socket.pack_sockaddr_in(port, host)
socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
socket.setsockopt(Socket::SOL_TCP, Socket::TCP_NODELAY, true)
socket.connect(address)
#socket = TCPSocket.new(host, port) # not help also
ssl_context = OpenSSL::SSL::SSLContext.new(:TLSv1)
ssl_context.cert = OpenSSL::X509::Certificate.new(File.open(sert_key))
ssl_context.key = OpenSSL::PKey::RSA.new(File.open(sert_key))
ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ssl_context)
ssl_socket.sync_close = true
ssl_socket.connect
sert = "hello"
sert = sert.force_encoding('UTF-8')
req = sprintf("%08x", sert.length) + sert
ssl_socket.write(req)
puts ssl_socket.read(4096)
但我有这样的错误:
test1.rb:30:在`connect'中:SSL_connect返回= 1 errno = 0 state = SSLv3读取服务器问候B:错误消息类型(OpenSSL :: SSL :: SSLError)
请帮我把这段代码移到ruby上。我不明白我想念的是什么(代码的区别)。
P.S。抱歉,我想连接的软件现在不能用于共享:(
答案 0 :(得分:1)
好像你应该使用这样的东西:
require 'socket'
require 'openssl'
host = '127.0.0.1'
port = 8963
sert_key = '../keys/key.pem'
socket = TCPSocket.new(host, port) # not help also
ssl_context = OpenSSL::SSL::SSLContext.new(:TLSv1)
ssl_context.cert = OpenSSL::X509::Certificate.new(File.open(sert_key))
ssl_context.key = OpenSSL::PKey::RSA.new(File.open(sert_key))
ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ssl_context)
ssl_socket.sync_close = true
ssl_socket.accept
sert = "hello"
sert = sert.force_encoding('UTF-8')
req = sprintf("%08x", sert.length) + sert
ssl_socket.write(req)
puts ssl_socket.sysread(4096)
编辑:又一次更新了代码。