Last active
December 7, 2018 04:45
-
-
Save fylooi/07f79da3c7f02ad3b52ffc2ca6da303e to your computer and use it in GitHub Desktop.
ruby-self-signed-certificate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cert_dir = "#{Dir.pwd}/config/certs" | |
Dir.mkdir(cert_dir) unless File.exists?(cert_dir) | |
localhost_key = "#{Dir.pwd}/#{File.join('config', 'certs', 'localhost.key')}" | |
localhost_cert = "#{Dir.pwd}/#{File.join('config', 'certs', 'localhost.crt')}" | |
unless File.exist?(localhost_key) | |
def generate_root_cert(root_key) | |
root_ca = OpenSSL::X509::Certificate.new | |
root_ca.version = 2 # cf. RFC 5280 - to make it a "v3" certificate | |
root_ca.serial = 0x0 | |
root_ca.subject = OpenSSL::X509::Name.parse "/C=BE/O=A1/OU=A/CN=*.localhost" | |
root_ca.issuer = root_ca.subject # root CA's are "self-signed" | |
root_ca.public_key = root_key.public_key | |
root_ca.not_before = Time.now | |
root_ca.not_after = root_ca.not_before + 2 * 365 * 24 * 60 * 60 # 2 years validity | |
root_ca.sign(root_key, OpenSSL::Digest::SHA256.new) | |
ef = OpenSSL::X509::ExtensionFactory.new | |
ef.subject_certificate = root_ca | |
ef.issuer_certificate = root_ca | |
root_ca.add_extension(ef.create_extension("basicConstraints","CA:TRUE",true)) | |
root_ca.add_extension(ef.create_extension("keyUsage","keyCertSign, cRLSign", true)) | |
root_ca.add_extension(ef.create_extension("subjectKeyIdentifier","hash",false)) | |
root_ca.add_extension(ef.create_extension("authorityKeyIdentifier","keyid:always",false)) | |
root_ca.add_extension(ef.create_extension("subjectAltName","DNS:*.localhost,IP:127.0.0.1",false)) | |
root_ca | |
end | |
root_key = OpenSSL::PKey::RSA.new(2048) | |
file = File.new( localhost_key, "wb") | |
file.write(root_key) | |
file.close | |
root_cert = generate_root_cert(root_key) | |
file = File.new( localhost_cert, "wb") | |
file.write(root_cert) | |
file.close | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment