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

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).

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,...>
Arne Hartherz About 4 years ago