如何使Ruby读取.cer public ssl key? [英] How do I make Ruby read .cer public ssl key?

查看:302
本文介绍了如何使Ruby读取.cer public ssl key?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个需要电子支付模块的RoR网站上工作。电子支付实现要求使用由它们提供的公共ssl密钥对xml数据进行编码。



我在Ruby中尝试做的:

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

如果我只是尝试打开该文件,它可以正常工作。但RSA.new()方法返回以下错误:

  OpenSSL :: PKey :: RSAError:PUB密钥和PRIV (irb)中的key :: nested asn1错误
:(初始化)
(来自(irb))5:在`new'
from(irb):5

从我在线文档中看到的一个.pem文件被使用,但我的公钥是public。 CER。这可能是问题吗?
在电子支付公司提供的PHP示例中,关键本身似乎也是一样的,相同的public.cer文件工作正常。



我是什么做错了?



谢谢,

解决方案

很可能是以DER编码的X.509证书。不幸的是,Ruby不会将OpenSSL接口暴露在DER中读取证书。所以你需要先把DER转换成PEM。这在Ruby中相当容易,

  b64 = Base64.encode64(File :: read(cert_file))
pem =----- BEGIN CERTIFICATE ----- \\\
#{b64} ----- END CERTIFICATE ----- \\\

cert = OpenSSL :: X509 ::证书$ new $ p

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,

解决方案

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

这篇关于如何使Ruby读取.cer public ssl key?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆