如何在Ruby中建立启用SSL的TCP / IP连接

时间:2021-01-18 23:56:08

I need to establish a TCP connection with my server which has a SSL enabled port, that I need to access.

我需要与我的服务器建立TCP连接,该服务器具有启用SSL的端口,我需要访问该端口。

I need to send a XML file and get the response from the server.

我需要发送一个XML文件并从服务器获取响应。

Before the SSL was enabled, I was able to get the data from the server using the below mentioned code.

在启用SSL之前,我能够使用下面提到的代码从服务器获取数据。

require 'socket'
myXML = 'test_xml' 
host = 'myhost.com'   
port = 12482               

socket = TCPSocket.open(host,port)  # Connect to server  
socket.send(myXML, 0)
response = socket.recvfrom(port)
puts response
socket.close

Now I have a 'certi.pfx' with which I need to establish a connection, Send my_xml data and get the response. How can this be done.

现在我有一个'certi.pfx',我需要建立一个连接,发送my_xml数据并获得响应。如何才能做到这一点。

I would also like to know if I have the 'pem' and 'key' file, how can I establish a connection, Send my_xml data and get the response.

我还想知道我是否有'pem'和'key'文件,如何建立连接,发送my_xml数据并获得响应。

Please help.

请帮忙。

2 个解决方案

#1


17  

require 'socket'
require 'openssl'

myXML = 'my_sample_data'
host = 'my_host.com'
port = my_port                

socket = TCPSocket.open(host,port)
ssl_context = OpenSSL::SSL::SSLContext.new()
ssl_context.cert = OpenSSL::X509::Certificate.new(File.open("certificate.crt"))
ssl_context.key = OpenSSL::PKey::RSA.new(File.open("certificate.key"))
ssl_context.ssl_version = :SSLv23
ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ssl_context)
ssl_socket.sync_close = true
ssl_socket.connect

ssl_socket.puts(myXML)
while line = ssl_socket.gets
  p line
end
ssl_socket.close

#2


3  

Like this:

喜欢这个:

  sock = TCPSocket.new('hostname', 443)
  ctx = OpenSSL::SSL::SSLContext.new
  ctx.set_params(verify_mode: OpenSSL::SSL::VERIFY_PEER)
  @socket = OpenSSL::SSL::SSLSocket.new(sock, ctx).tap do |socket|
    socket.sync_close = true
    socket.connect
  end

#1


17  

require 'socket'
require 'openssl'

myXML = 'my_sample_data'
host = 'my_host.com'
port = my_port                

socket = TCPSocket.open(host,port)
ssl_context = OpenSSL::SSL::SSLContext.new()
ssl_context.cert = OpenSSL::X509::Certificate.new(File.open("certificate.crt"))
ssl_context.key = OpenSSL::PKey::RSA.new(File.open("certificate.key"))
ssl_context.ssl_version = :SSLv23
ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ssl_context)
ssl_socket.sync_close = true
ssl_socket.connect

ssl_socket.puts(myXML)
while line = ssl_socket.gets
  p line
end
ssl_socket.close

#2


3  

Like this:

喜欢这个:

  sock = TCPSocket.new('hostname', 443)
  ctx = OpenSSL::SSL::SSLContext.new
  ctx.set_params(verify_mode: OpenSSL::SSL::VERIFY_PEER)
  @socket = OpenSSL::SSL::SSLSocket.new(sock, ctx).tap do |socket|
    socket.sync_close = true
    socket.connect
  end