Last Updated: September 03, 2024
·
6.931K
· Lex S

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.

1 Response
Add your response

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.not
after = Time.now + 365 * 24 * 60 * 60 # 1 year validity

ef = OpenSSL::X509::ExtensionFactory.new
ef.subjectcertificate = cert
ef.issuer
certificate = cert
cert.extensions = [
ef.createextension("basicConstraints","CA:TRUE", true),
ef.create
extension("subjectKeyIdentifier", "hash"),
ef.createextension("authorityKeyIdentifier", "keyid:always,issuer:always"),
]
cert.add
extension 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.to
pem)

over 1 year ago ·