Getting Openssl::X509::Certificateerror Nested Asn1 Error on Ruby

Ruby OpenSSL nested asn1 error

So, once again, I answered my own question. I was trying to read a DER-form pkcs12. I had to convert it to PEM format.

Certificate to pem to certificate not working: nested asn1 error

So I got the answer myself. The certificate needs at least these information:

cert = OpenSSL::X509::Certificate.new
cert.version = 2
cert.serial = 0
cert.not_before = Time.now
cert.not_after = Time.now + 3600
cert.public_key = key.public_key
cert.sign key, OpenSSL::Digest::SHA1.new

Then this is possible:

OpenSSL::X509::Certificate.new(cert.to_pem) => returns

Ruby Error reading in Certificate File with OpenSSL

"testuser.p12" seems to be a PKCS#12 file according to the postfix. Reading PKCS#12 format as X.509 certificate format causes ASN.1 decoding error.

You should do OpenSSL::PKCS12.new(File.read("testuser.p12")) instead. If the file is protected with passphrase (it's normal), give the passphrase as the second parameter for PKCS12.new like OpenSSL::PKCS12.new(File.read("testuser.p12"), "pass")

You can extract certificate and CA certificates by PKCS12#certificate and PKCS12#ca_certs methods.

p12 = OpenSSL::PKCS12.new(File.read("testuser.p12"), "pass")
p p12.certificate
p p12.ca_certs

Rails can't read certificate information from environment due to nested asn1 error

I finally found a way to do it... mixing it all up!

So the file, for example company.key looks like

-----BEGIN PRIVATE RSA KEY ----
Mumbojumbomummbojumbo
-----END RSA PRIVATE KEY----

So I switched it to a one liner, making explicit \n in the string (so its a real \n)

COMPANY_KEY=""-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA+ztKEj\n-----END RSA PRIVATE KEY-----\n"

Don't forget the last \n in the file.

Now, the last part, in the place where I used to do

@private_key = OpenSSL::PKey::RSA.new(File.read(private_key_file))

Now I do

@private_key = OpenSSL::PKey::RSA.new(ENV['COMPANY_KEY'].gsub("\\n", "\n"))

And now works like a charm! No public certificates, every piece of info in environment variables.



Related Topics



Leave a reply



Submit