Generate a self-signed X509 certificate with ruby
Create a public X509 certificate called 'certificate.pem' and a private rsa key called 'private_key.pem':
require "openssl"
key = OpenSSL::PKey::RSA.new 4096
name = OpenSSL::X509::Name.parse '/CN=nobody'
cert = OpenSSL::X509::Certificate.new
cert.version = 2
cert.serial = 0
cert.not_before = Time.now
cert.not_after = Time.now + 606024364.251
cert.publickey = key.publickey
cert.subject = name
cert.issuer = name
cert.sign key, OpenSSL::Digest.new('SHA256')
open 'certificate.pem', 'w' do |io| io.write cert.to_pem end
open 'privatekey.pem', 'w' do |io| io.write key.topem end
The ruby openssl docs have other great examples.
Mailer To Go is an email provider on Heroku that is by developers for developers.
We've spend too much time dealing with other mailing services, and decided to create our own.
Written by Lex S
Related protips
2 Responses
require 'openssl'
key = OpenSSL::PKey::RSA.new(2048)
publickey = key.publickey
name = OpenSSL::X509::Name.parse("CN=example.com")
cert = OpenSSL::X509::Certificate.new
cert.version = 2
cert.serial = 0
cert.subject = name
cert.issuer = name
cert.publickey = publickey
cert.notbefore = Time.now
cert.notafter = Time.now + 365 * 24 * 60 * 60 # 1 year validity
ef = OpenSSL::X509::ExtensionFactory.new
ef.subjectcertificate = cert
ef.issuercertificate = cert
cert.extensions = [
ef.createextension("basicConstraints","CA:TRUE", true),
ef.createextension("subjectKeyIdentifier", "hash"),
ef.createextension("authorityKeyIdentifier", "keyid:always,issuer:always"),
]
cert.addextension ef.create_extension("authorityKeyIdentifier", "keyid:always,issuer:always")
cert.sign(key, OpenSSL::Digest::SHA256.new)
File.write('example.com.crt', cert.topem)
File.write('example.com.key', key.topem)
Thanks for sharing your version, Hitul. The added extensions, like basicConstraints and authorityKeyIdentifiers, are a helpful touch, especially if the certificate needs to be recognized more formally or used in test CA setups. I noticed a small syntax issue in the cert.t extensions array, though, it looks like cert r addextension is used inside the array itself, which might throw an error. Probably better to call cert. Add extension separately after setting cert extensions. Other than that, really useful addition!