-
-
Save gnuos/b3444b88f3827e3a99713c09414546ad to your computer and use it in GitHub Desktop.
Generating a SAN Certificate in Ruby
This file contains hidden or 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
| require 'openssl' | |
| require 'openssl-extensions/all' | |
| keyfile = '/tmp/mycert.key' | |
| csrfile = '/tmp/mycert.csr' | |
| file = File.new(keyfile,'w',0400) | |
| key = OpenSSL::PKey::RSA.new 2048 | |
| file.write(key) | |
| file.close | |
| cert_name = [ ['CN','myhost.example.com'], ['DC','example'], ['DC','com']] | |
| sans = [ 'www.example.com', 'example.com' ] | |
| # our OpenSSL x509 Name entry for our cert subject | |
| x509_subject_entry = OpenSSL::X509::Name.new(cert_name) | |
| # Our OpenSSL x509 certificate request | |
| request = OpenSSL::X509::Request.new | |
| request.version = 0 | |
| request.subject = x509_subject_entry | |
| request.public_key = key.public_key | |
| # setup our certificate extensions. these may or may not match your need | |
| exts = [ | |
| [ "basicConstraints", "CA:FALSE", false ], | |
| [ "keyUsage", "Digital Signature, Non Repudiation, Key Encipherment", false], | |
| ] | |
| # SANs are just another extension, so we'll add them here | |
| sans.map! do |san| | |
| san = "DNS:#{san}" | |
| end | |
| # add our subjectAltName extension containing our SANs | |
| exts << [ "subjectAltName", sans.join(','), false ] | |
| # use extension factory to generate the OpenSSL extension structures | |
| ef = OpenSSL::X509::ExtensionFactory.new | |
| exts = exts.map do |ext| | |
| ef.create_extension(*ext) | |
| end | |
| attrval = OpenSSL::ASN1::Set([OpenSSL::ASN1::Sequence(exts)]) | |
| attrs = [ | |
| OpenSSL::X509::Attribute.new('extReq', attrval), | |
| OpenSSL::X509::Attribute.new('msExtReq', attrval), | |
| ] | |
| attrs.each do |attr| | |
| request.add_attribute(attr) | |
| end | |
| request.sign(key, OpenSSL::Digest::SHA1.new) | |
| file = File.new(csrfile,'w',0400) | |
| file.write(request) | |
| file.close | |
| puts request.to_text |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment