I'm trying to generate a self-signed certificate in ruby, but am running into trouble. This is what I currently have right now:
require 'openssl'
if ARGV.length != 3 then
puts "USAGE: #{__FILE__} <type[der|pem]> <private-out> <public-out>"
exit
end
type = ARGV[0].downcase
privateKeyFile = ARGV[1]
publicKeyFile = ARGV[2]
values = [{ 'C' => 'US'},
{'ST' => 'SomeState'},
{ 'L' => 'SomeCity'},
{ 'O' => 'Organization'},
{'OU' => 'Unit'},
{'CN' => "somesite.com"}]
name = values.collect{ |l| l.collect { |k, v| "/#{k}=#{v}" }.join }.join
key = OpenSSL::PKey::RSA.generate(1024)
pub = key.public_key
ca = OpenSSL::X509::Name.parse(name)
cert = OpenSSL::X509::Certificate.new
cert.version = 2
cert.serial = 1
cert.subject = ca
cert.issuer = ca
cert.public_key = pub
cert.not_before = Time.now
cert.not_before = Time.now + (360 * 24 * 3600)
File.open(privateKeyFile + "." + type, "w") {|f| f.write key.send("to_#{type}") }
File.open(publicKeyFile + "." + type, "w") {|f| f.write cert.send("to_#{type}") }
When I try to use the generated private key and certificate in apache, I get this error:
[Thu Mar 04 10:58:44 2010] [error] Init: Unable to read server certificate from file /etc/ssl/certs/gnarly.pem
[Thu Mar 04 10:58:44 2010] [error] SSL Library Error: 218529960 error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Thu Mar 04 10:58:44 2010] [error] SSL Library Error: 218595386 error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error
This is what my certificate says:
-----BEGIN CERTIFICATE-----
<lots of stuff>
-----END CERTIFICATE-----
It calls itself a certificate instead of a CSR, which is what most of the things I've found online say about that apache2 error (that I might have gotten the CSR and CERT mixed up). My guess is that I'm not generating the right type of certificate. Maybe I have to change the serial or version attributes. Also, I'm not doing any self-signing anywhere, not that I know of anyways. I know you can do something like this though:
require "openssl"
key = OpenSSL::PKey::RSA.generate(1024)
signature = key.sign(OpenSSL::Digest::SHA1.new, "data to sign")
Reminder: My goal is to generate a self-signed certificate, in case my long-ish question lost focus on the way.
EDIT: I guess the real question is how to sign a certificate with a key