如何在 Ruby 中建立启用 SSL 的 TCP/IP 连接 [英] How to establish a SSL enabled TCP/IP Connection in Ruby

查看:54
本文介绍了如何在 Ruby 中建立启用 SSL 的 TCP/IP 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

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

现在我有一个certi.pfx",我需要与它建立连接,发送 my_xml 数据并获得响应.这是怎么做到的.

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.

我还想知道如果我有pem"和key"文件,我如何建立连接,发送 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.

请帮忙.

推荐答案

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

这篇关于如何在 Ruby 中建立启用 SSL 的 TCP/IP 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆