views:

392

answers:

1

Hey,

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,

A: 

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.b64encode(File::read(cert_file), 64)
pem = "-----BEGIN CERTIFICATE-----\n#{b64}-----END CERTIFICATE-----\n"
cert = OpenSSL::X509::Certificate.new(pem)
public_key = cert.public_key
ZZ Coder
I have tried your solution and it works fine until I do: "cert = OpenSSL::X509::Certificate.new(pem)" at which point it gives me the same error message. Also I have noticed some "\n" characters in the certificate code, could this be the problem? Thanks
Brayn
Yes. There is an extra \n. I edited the code.
ZZ Coder
I have tried the new version of the code with no luck. Thanks anyway.
Brayn
If you post a hexdump of the file, I may be able to find out the problem.
ZZ Coder