在Ruby上获取OpenSSL :: X509 :: CertificateError嵌套asn1错误

时间:2014-06-17 12:29:04

标签: ruby apple-push-notifications

我有来自Apple的.p12文件,并尝试使用以下命令将其转换为.pem文件:

openssl pkcs12 -in cert.p12 -out apple_push_notification_development.pem -nodes -clcerts

使用

尝试创建新的OpenSSL :: X509 :: Certificate对象时
OpenSSL::X509::Certificate.new(File.read('apple_push_notification_development.pem'))

我收到以下错误:

OpenSSL::X509::CertificateError: nested asn1 error
    from (irb):9:in `initialize'
    from (irb):9:in `new'
    ...

我做错了什么吗?卡住了,请帮忙。 感谢

3 个答案:

答案 0 :(得分:13)

感谢它并非完全相同的情况,但我试图在我的实例中读取PEM文件(PKCS7)。 OpenSSL CLI可以很好地解码它,但是当我试图将它加载到对象中时,ruby会继续抛出你描述的嵌套asn1错误。

在我的情况下,它需要一个新的行,即' \ n'在PEM文件的末尾,它接受它。

只有当我创建一个空对象并将生成的PEM输出与我尝试加载的文件进行比较时,我才能解决这个问题。

所以使用X509证书可能会尝试:

cert = OpenSSL::X509::Certificate.new
cert.to_pem
=> "-----BEGIN CERTIFICATE-----\nMCUwGwIAMAMGAQAwADAEHwAfADAAMAgwAwYBAAMBADADBgEAAwEA\n-----END CERTIFICATE-----\n"

并将其与您的PEM文件进行比较

正如您所看到的那样,它以新行终止,并且在我尝试导入的文件中丢失了。

答案 1 :(得分:10)

我遇到了同样的问题,我需要用Base64解码文件内容。

require 'openssl'
require 'base64'

encoded_content = File.read('apple_push_notification_development.pem')
decoded_content = Base64.decode64(encoded_content)
certificate = OpenSSL::X509::Certificate.new(decoded_content)

答案 2 :(得分:5)

当您忘记签署新生成的证书时,也可能发生这种情况。我想使用自签名证书,但忘记了签名部分。

# Create key
key = OpenSSL::PKey::RSA.new(2048)
open("key.pem", "w") do |io| io.write(key.to_pem) end

# Generate certificate
name = OpenSSL::X509::Name.parse("CN=example.com/C=EE")
cert = OpenSSL::X509::Certificate.new
cert.version     = 2
cert.serial      = 0
cert.not_before  = Time.now
cert.not_after   = cert.not_before + 1 * 365 * 24 * 60 * 60 # 1 year validity
cert.public_key  = key.public_key
cert.subject     = name

这部分代码是我错过的:

cert.issuer = name
cert.sign key, OpenSSL::Digest::SHA1.new
open "cert.pem", 'w' do |io| io.write cert.to_pem end