Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Export" x509 certificate in Ruby

I'm communicating with an API that has the following directions:

  1. Install the issued x509 certificate onto the client server.
  2. Export the x509 certificate using the supplied password and default Machine Key Set into memory.
  3. Base64 encode the exported bytes of the x509 certificate.
  4. Add ‘X509Certificate’ as an HTTP header and set its value to the result of step 3.

Step 1 and 4 are easy, but I have no idea on 2 or or the 'export' portion of 3. I have tried Googling for some time and I'm not sure exactly where to even really start.

Would someone point me in the right direction on how to "export" a certificate with "machine key set"?

Here is what I have so far

raw_data = File.read('cert.pfx')
pkcs = OpenSSL::PKCS12.new(raw_data, 'password')
cert = OpenSSL::X509::Certificate.new(pkcs.certificate.to_pem)

Here is equivalent .NET code:

public string GetBase64Cert(string certificateThumbprint)
 {
 using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
 {
 store.Open(OpenFlags.ReadOnly);
 var foundCertificates = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
 if (foundCertificates.Count != 1)
 {
 return null;
 }
 var certByteArray = foundCertificates[0].Export(X509ContentType.Cert);
 store.Close();
 return Convert.ToBase64String(certByteArray);
 }
}

And equivalent PHP code:

public function setx509($x509file) {
  $cert = openssl_x509_parse($x509file);
  $base64cert = base64_encode($cert);
  return $base64cert;
}
like image 783
Tallboy Avatar asked Jul 01 '26 02:07

Tallboy


1 Answers

Try

pkcs = OpenSSL::PKCS12.new(File.read('cert.pfx'), 'password')
str = Base64.urlsafe_encode64(pkcs.certificate.to_der)

Probably also str.gsub(/=+$/, '') to cut off padding

like image 64
Vasfed Avatar answered Jul 03 '26 18:07

Vasfed