@kyanny's blog

My thoughts, my life. Views/opinions are my own.

Ruby: WEBrick で HTTPS サーバを立てる (2)

Ruby: WEBrick で HTTPS サーバを立てる - @kyanny's blog では不十分だったので改良版。

TODO:

既存の証明書と鍵を使う場合

#!/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