Ruby: WEBrick で HTTPS サーバを立てる - @kyanny's blog では不十分だったので改良版。
TODO:
OpenSSL::PKey.read
は鍵の種類を自動判別してくれるので RSA の場合と ECDSA の場合で実装を分ける必要ない。後で更新するOpenSSL::PKey.read
は C 拡張で実装されてるメソッドなので source_location では辿れない。実装は ext/openssl/ossl_pkey.c のossl_pkey_new_from_data
https://github.com/ruby/openssl/blob/bff06067cd3cf611b50cb76adc2ae40f9406cb1e/ext/openssl/ossl_pkey.c#L206-L224
既存の証明書と鍵を使う場合
#!/usr/bin/env ruby require 'webrick' require 'webrick/https' require 'openssl' options = { :Port => 8080, :DocumentRoot => "./", :SSLEnable => true, :SSLCertificate => OpenSSL::X509::Certificate.new(File.open("./cert.pem")), :SSLPrivateKey => OpenSSL::PKey::RSA.new(File.read("./privkey.pem")), } server = WEBrick::HTTPServer.new(options) trap 'INT' do server.shutdown end # server.mount_proc "/" do |req, res| # res.body = "Hi, it's #{Time.now.to_s}!" # end server.start
鍵が RSA ではなく ECDSA の場合
#!/usr/bin/env ruby require 'webrick' require 'webrick/https' require 'openssl' options = { :Port => 8080, :DocumentRoot => "./", :SSLEnable => true, :SSLCertificate => OpenSSL::X509::Certificate.new(File.open("./cert.pem")), # https://stackoverflow.com/a/38936194/374851 :SSLPrivateKey => OpenSSL::PKey.read(File.read("./privkey.pem")), } server = WEBrick::HTTPServer.new(options) trap 'INT' do server.shutdown end # server.mount_proc "/" do |req, res| # res.body = "Hi, it's #{Time.now.to_s}!" # end server.start
WEBrick に自己署名証明書を自動生成させる場合
#!/usr/bin/env ruby require 'webrick' require 'webrick/https' require 'openssl' options = { :Port => 8080, :DocumentRoot => "./", :SSLEnable => true, :SSLCertName => [["CN", "localhost.example.com"]], } server = WEBrick::HTTPServer.new(options) trap 'INT' do server.shutdown end # server.mount_proc "/" do |req, res| # res.body = "Hi, it's #{Time.now.to_s}!" # end server.start