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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)