Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make Ruby read .cer public ssl key?

I am working on a RoR website that requires an e-payment module. The e-payment implementation requires that the xml data is encoded using a public ssl key provided by them.

What I tried to do in Ruby:

public_key = OpenSSL::PKey::RSA.new(File.read(public_key_file))

If I just try to open the file separately it works fine. But the RSA.new() method returns the following error:

OpenSSL::PKey::RSAError: Neither PUB key nor PRIV key:: nested asn1 error
    from (irb):5:in `initialize'
    from (irb):5:in `new'
    from (irb):5

From what I've seen in the online documentation a .pem file is used but my public key is something like public.cer. Could that be the problem ? The key itself seems to be OK for in the PHP example provided by the e-payment company the same public.cer file works fine.

What am I doing wrong?

Thanks,

like image 384
Brayn Avatar asked Feb 25 '26 21:02

Brayn


1 Answers

The .cer file is most likely a X.509 certificate encoded in DER. Unfortunately, Ruby doesn't expose the OpenSSL interface to read certificate in DER. So you need to convert the DER to PEM first. This is fairly easy in Ruby,

b64 = Base64.encode64(File::read(cert_file))
pem = "-----BEGIN CERTIFICATE-----\n#{b64}-----END CERTIFICATE-----\n"
cert = OpenSSL::X509::Certificate.new(pem)
public_key = cert.public_key
like image 131
ZZ Coder Avatar answered Feb 28 '26 09:02

ZZ Coder