Ruby + openssl + self signed certificates = confusion

N

Neumann

I'm trying to work a bit of CA ability into some code that I'm writing,
and I need to create a self-signed certificate. This is not going so
well. I'm able to create the certificate, and it seems to work OK,
until I save it. The sample code I use to create a test certificate is
as follows:

entries = {"countryName" => "USA", "stateOrProvinceName" => "New
Mexico", "localityName" => "Albuquerque", "organizationName" => "That
group of dudes", "organizationalUnitName" => "The cool dudes",
"commonName" => "William D. Neumann"}
keypair2048 = PKey::RSA.new(2048) { putc "." }
name = X509::Name.new()
entries.each { |_k,_v| name.add_entry(_k,_v) }
cert = Certificate.new
cert.public_key = keypair2048.public_key
cert.subject = name
cert.issuer = name
cert.version = 2
now = Time.now.utc
next_year = now + (365 * 24 * 60 * 60)
cert.not_before = now
cert.not_after = next_year
ef = ExtensionFactory.new
bc = ef.create_extension("basicConstraints", "CA:TRUE")
ku = ef.create_extension("keyUsage", "keyEncipherment,
digitalSignature")
cert.extensions = [bc, ku]
cert.sign(keypair2048, Digest::SHA1.new)

Now, when I test the signature on this certificate, all is well:
irb(main):099:0> cert.verify cert.public_key
=> true

But if I save the certificate and read it back in, I have no such luck:
File.open("newcert.pem","w") do |_file|
_file << cert.to_pem
end

newcert = Certificate.new(File.read "newcert.pem")
irb(main):105:0> newcert.verify newcert.public_key
=> false
irb(main):106:0> newcert.verify cert.public_key
=> false

But oddly enough, this works.

irb(main):107:0> cert.verify newcert.public_key
=> true

Also, if I create a different certificate, and sign it using cert's
key, I can save it, read it back in and verify it with cert's public
key (and newcert's as well) just fine. Does anyone know what's going
on here with the self signed certificate?
 

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top