如何让 Ruby 读取 .cer 公共 ssl 密钥?
我正在开发一个需要电子支付模块的 RoR 网站。电子支付实现要求使用他们提供的公共 ssl 密钥对 xml 数据进行编码。
我在 Ruby 中尝试做的事情:
public_key = OpenSSL::PKey::RSA.new(File.read(public_key_file))
如果我只是尝试单独打开文件,它就可以正常工作。但 RSA.new() 方法返回以下错误:
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
根据我在在线文档中看到的内容,使用了 .pem 文件,但我的公钥类似于 public.cer。这可能是问题所在吗? 密钥本身似乎没问题,因为在电子支付公司提供的 PHP 示例中,相同的 public.cer 文件工作正常。
我做错了什么?
谢谢,
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,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
.cer 文件很可能是以 DER 编码的 X.509 证书。不幸的是,Ruby 没有公开 OpenSSL 接口来读取 DER 中的证书。所以你需要先将DER转换为PEM。这在 Ruby 中相当容易,
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,
只是一个更新 - ruby 1.9.3 的当前 openssl gem 支持从 DER 和 PEM 格式的文件中读取证书。
请参阅文档 http:// /www.ruby-doc.org/stdlib-1.9.3/libdoc/openssl/rdoc/OpenSSL/X509/Certificate.html。
Just an update - the current openssl gem for ruby 1.9.3 supports reading certificates from file in DER and PEM format.
See the documentation at http://www.ruby-doc.org/stdlib-1.9.3/libdoc/openssl/rdoc/OpenSSL/X509/Certificate.html.
您可以在此处找到有关证书不同编码的信息:http://www.gtopia.org/blog/2010/02/der-vs-crt-vs-cer-vs-pem-certificates/
尝试将您的证书从 der 格式转换到pem。
You can find information about the different encodings for certificates here: http://www.gtopia.org/blog/2010/02/der-vs-crt-vs-cer-vs-pem-certificates/
Try to convert your certificate from der format to pem.
尝试将
File.read
替换为File.binread
。根据您的平台(Windows 最容易受影响)
File.read
可能不会返回您期望的结果。使用 File.binread 将确保您获得正在读取并想要使用的二进制证书的实际二进制数据。有关差异的一些背景:https://stackoverflow.com/a/30081354/252627
Try replacing
File.read
withFile.binread
.Depending on your platform (Windows is most susceptible)
File.read
may not return what you expect. UsingFile.binread
will make sure you get the actual binary data of the binary certificate you are reading and want to work with.Some background on the difference: https://stackoverflow.com/a/30081354/252627