Posted 4 months ago. Visible to the public.

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('', 443, use_ssl: true) { |http| http.peer_cert } # => #<OpenSSL::X509::Certificate: subject=#<OpenSSL::X509::Name,...> 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: subject=#<OpenSSL::X509::Name,...>

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Arne Hartherz
Last edit:
4 months ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more