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
How to Robustly Parse Malformed CSV
How to Write Rake Task to Import Data to Rails App
How to Remove a Node with Nokogiri
Doing a Http Basic Authentication in Rails
Rails - Pass Id Parameter on a Link_To
Failing Installing Pg Gem, "Mkmf.Rb Can't Find Header Files for Ruby" (MAC Osx 10.6.5)
Check If Internet Connection Exists with Ruby
Loaderror Running Mongrel with Rails3 and Ruby 1.9.2
How to Get Indexes of All Occurrences of a Pattern in a String
Why Doesn't Ruby Have a Real Stringbuffer or Stringio
How to Check the Database Type in a Rails Migration
Difference Between Integer(Value) and Value.To_I
What Does "+=" (Plus Equals) Mean
How to Remove '---' on Top of a Yaml File
The Compiler Failed to Generate an Executable File. (Runtimeerror)