Reading an SSL Cert in Ruby Over a Socket

Posted 13 Jan 2013 to ruby, ssl and has Comments

I couldn’t find any examples of reading a SSL certificate from a socket connection, so I thought I’d share my approach here. Ultimately, I just wanted to get the X509 certificate information for a few websites that have HTTPS - which this bit of code will do.

require 'socket'
require 'openssl'

tcp_client ="", 443)
ssl_client =
cert =
certprops =
issuer = { |name, data, type| name == "O" }.first[1]
results = { 
            :valid_on => cert.not_before,
            :valid_until => cert.not_after,
            :issuer => issuer,
            :valid => (ssl_client.verify_result == 0)

The last line creates a hash that contains when the cert became valid, when it will become invalid, who issued it, and whether or not it actually is valid.