Forever-valid SSL certificates

drbrain | Wed, 11 Jan 2012 22:04:00 GMT

Posted in ,

If your library uses X509 cryptography, naturally your tests will need a key and valid certificate to test against. Creating a key and certificate frequently can quickly drain your entropy pool which slows down your tests.

Instead of creating the key for every test startup you can create it once and load it off the disk like this:

class TestMyGem < MyGem::TestCase
  private_key = File.expand_path '../../../test/private_key.pem', __FILE__
  private_key = File.read private_key
  PRIVATE_KEY = OpenSSL::PKey::RSA.new private_key

  # …

Sure, you can rebuild the certificate every time with a validity time of an hour, but why not create a forever-valid certificate to go with it? No reasonable person would ever use a key shipped with an open project anyhow. Here's how to generate such a key and certificate:

require 'openssl'

# purposefully short key length
key = OpenSSL::PKey::RSA.new 512

# bogus subject and issuer
name = OpenSSL::X509::Name.parse 'CN=nobody/DC=example'
cert = OpenSSL::X509::Certificate.new
cert.subject = name
cert.issuer = name
cert.version = 2
cert.serial = 1
cert.not_before = Time.now

# lasts as long as X509 allows
cert.not_after = Time.gm 9999, 12, 31, 23, 59, 59
cert.public_key = key.public_key

cert.sign key, OpenSSL::Digest::SHA1.new

open 'private_key.pem', 'w' do |io| io.write key.to_pem end
open 'public_cert.pem', 'w' do |io| io.write cert.to_pem end

You can load this certificate just like the key as described above:

  public_cert = File.expand_path '../../../test/public_cert.pem', __FILE__
  public_cert = File.read public_cert
  PUBLIC_CERT = OpenSSL::X509::Certificate.new public_cert
comment

Comments RSS FEED

Comments are disabled