Created
March 9, 2018 06:55
-
-
Save maloninc/9e7cfc68decc19dbc9ab4d4cff2b6afa to your computer and use it in GitHub Desktop.
Ruby: Create localhost SSL/TLS certificate accepted by modern browsers
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
# | |
# Modern browsers don't accept self-signed localhost certificates. | |
# So you have to create CA's certificate and key before creating localhost certificate. | |
# I wrote a ruby method to do thease all tasks. | |
# | |
def create_self_signed_root_ca_signed_cert(bits, cn, comment) | |
year = 100 | |
ca = OpenSSL::X509::Name.new | |
ca.add_entry 'CN', 'localhost CA' | |
# Create CA's key | |
ca_key = OpenSSL::PKey::RSA.generate bits | |
# Create CA's certificate | |
ca_cer = OpenSSL::X509::Certificate.new | |
ca_cer.not_before = Time.now | |
ca_cer.not_after = Time.now + year*365*24*60*60 | |
ca_cer.public_key = ca_key.public_key | |
ca_cer.serial = 1 | |
ca_cer.issuer = ca | |
ca_cer.subject = ca | |
ex = OpenSSL::X509::Extension.new 'basicConstraints', OpenSSL::ASN1.Sequence([OpenSSL::ASN1::Boolean(true)]) | |
ca_cer.add_extension ex | |
ca_cer.sign ca_key, OpenSSL::Digest::SHA256.new | |
# Create server's key | |
rsa = OpenSSL::PKey::RSA.generate bits | |
# Create server's certificate and sign with CA's key | |
cert = OpenSSL::X509::Certificate.new | |
cert.version = 2 | |
cert.serial = 1 | |
name = (cn.kind_of? String) ? OpenSSL::X509::Name.parse(cn) | |
: OpenSSL::X509::Name.new(cn) | |
cert.subject = name | |
cert.issuer = ca_cer.subject | |
cert.not_before = Time.now | |
cert.not_after = Time.now + (year*365*24*60*60) | |
cert.public_key = rsa.public_key | |
ef = OpenSSL::X509::ExtensionFactory.new(nil,cert) | |
ef.issuer_certificate = cert | |
cert.extensions = [ | |
ef.create_extension("basicConstraints","CA:FALSE"), | |
ef.create_extension("keyUsage", "keyEncipherment"), | |
ef.create_extension("subjectKeyIdentifier", "hash"), | |
ef.create_extension("extendedKeyUsage", "serverAuth"), | |
ef.create_extension("nsComment", comment), | |
] | |
aki = ef.create_extension("authorityKeyIdentifier", "keyid:always,issuer:always") | |
cert.add_extension(aki) | |
cert.sign(ca_key, OpenSSL::Digest::SHA256.new) | |
return [ cert, rsa ] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment