Skip to content

Instantly share code, notes, and snippets.

@arusso
Last active June 1, 2021 21:20
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save arusso/d5a3195773c2ca3717d4 to your computer and use it in GitHub Desktop.
Save arusso/d5a3195773c2ca3717d4 to your computer and use it in GitHub Desktop.
Generating a SAN Certificate in Ruby
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
@whitehat101
Copy link

I had to remove require 'openssl-extensions/all' to get this to run, but it worked great after. Excellent code. You'll probably want a SHA2 signature (OpenSSL::Digest::SHA256, instead of OpenSSL::Digest::SHA1), if you're looking to use this cert on the modern Internet.

I'd at least recommend looking into R509 if you're going to be doing considerable work with certificates. Their abstraction is complete, and high level. The above roughy translates to:

require 'r509'
csr = R509::CSR.new(
  :subject => [['CN','something.com']],
  :san_names => ["something2.com","something3.com"]
)
puts csr.key.to_pem
puts csr.to_pem

However, I wasn't able to reverse engineer r509 easily, and it's useful to see how this can be achieved with just Ruby's standard libraries.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment