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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)