I recently needed to deal with ssl connection using client side certificates. The ruby openssl bindings are fairly impenetrable, here's what worked for me (at least in part as a note for myself in the future)

ctx = OpenSSL::SSL::SSLContext.new
ctx.cert = OpenSSL::X509::Certificate.new("mycert.cer")
ctx.key = OpenSSL::PKey::RSA.new("mykey.pem")
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.connect

If the key you've got is a .p12 file (which is what the key chain utility on the mac exports) then you'll need to convert it like so

openssl pkcs12 -in key.p12  -nocerts -nodes -out key.pem

3 Responses to “ruby openssl and client side certificates”

  1. paul harrington Says:
    is a .p12 file a PKCS12 cert? if so, I'd think the following code should work... ctx = OpenSSL::SSL::SSLContext.new pkcs12 = OpenSSL::PKCS12.new(File.read("mycert.p12")) ctx.cert = pkcs12.certificate ctx.key = pkcs12.key
  2. paul harrington Says:
    sorry, looks like that needs to be: pkcs12 = OpenSSL::PKCS12.new(File.read("cert.p12"), "") I'm going off a rather hackish utility i wrote rather early this year, so sorry if all of this is completely wrong :\
  3. Fred Says:
    Ah brilliant, so I didn't need to do the dance to turn the .p12 file into something else. I find the ruby openssl libraries nearly inscrutable - only got what I have by reading the jruby tests for their openssl replacement!

Sorry, comments are closed for this article.