Read more

Ruby: How to fetch a remote host's TLS certificate

Arne Hartherz
March 09, 2020Software engineer at makandra GmbH

TLS/SSL certificates are often used for HTTPS traffic. Occasionally a service may also use their TLS certificate to support public-key encrypting data (e.g. when it is part of the URI and visible to the user, but contains sensitive information).

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Here is how to easily fetch such certificate data.

certificate = Net::HTTP.start('example.com', 443, use_ssl: true) { |http| http.peer_cert }
# => #<OpenSSL::X509::Certificate: subject=#<OpenSSL::X509::Name CN=www.example.org,...>

certificate.public_key
# => #<OpenSSL::PKey::RSA:0x00007f46a8731978>

Note how this does not send a full request, but only establishes an HTTPS connection to extract the certificate.
Net::HTTP will complain about invalid or mismatching certificates automatically.

If you need a string representation of the certificate to cache or persist it, you can use to_pem:

certificate_data = certificate.to_pem
# => "-----BEGIN CERTIFICATE-----\nMIIHQDCCBiigAwIBAgIQD9B43Ujxor1NDyupa2A4/jANBgkqh..."

You can then instantiate a Certificate from that string:

certificate = OpenSSL::X509::Certificate.new(certificate_data)
# => #<OpenSSL::X509::Certificate: subject=#<OpenSSL::X509::Name CN=www.example.org,...>
Posted by Arne Hartherz to makandra dev (2020-03-09 14:50)