LoginSignup
11
4

More than 5 years have passed since last update.

SSL/TLS 証明書の情報を Ruby で取得する

Last updated at Posted at 2017-02-03

実装

require 'socket'
require 'openssl'

def get_certificate(host)
  certificate = nil

  TCPSocket.open(host, 443) do |tcp_client|
    ssl_client = OpenSSL::SSL::SSLSocket.new(tcp_client)
    ssl_client.hostname = host
    ssl_client.connect
    certificate = ssl_client.peer_cert
    ssl_client.close
  end

  certificate
end

上記の get_certificate メソッドは、ホスト名を引数に取り、OpenSSL::X509::Certificate オブジェクトを返す。OpenSSL::X509::Certificate は X509 証明書を表すクラスで、このオブジェクトは証明書のさまざまな情報、例えば公開鍵や発行者、有効期限などを持っている。

get_certificate('qiita.com')
=> #<OpenSSL::X509::Certificate
 subject=#<OpenSSL::X509::Name CN=*.qiita.com,OU=Domain Control Validated - RapidSSL(R),OU=See www.rapidssl.com/resources/cps (c)15,OU=GT01505012>,
 issuer=#<OpenSSL::X509::Name CN=RapidSSL SHA256 CA - G3,O=GeoTrust Inc.,C=US>,
 serial=#<OpenSSL::BN 195919>,
 not_before=2015-03-15 03:55:03 UTC,
 not_after=2017-05-16 01:59:04 UTC>

使用例

SSL/TLS 証明書の有効期限を調べてみる。


require 'active_support'
require 'active_support/core_ext'

certificate = get_certificate('qiita.com')
not_after = certificate.not_after.in_time_zone('Japan')

diff = ((not_after - Time.now) / 1.days)

def time2str(time)
  d = time.strftime('%Y/%m/%d')
  w = %w(日 月 火 水 木 金 土)[time.wday]
  t = time.strftime('%H:%M:%S')

  "#{d} (#{w}) #{t}"
end

puts("有効期限: #{time2str(not_after)} (残り #{diff.to_i} 日)")
有効期限: 2017/05/16 10:59:04 (火) 10:59:04 (残り 101 日)

参考

11
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
4