Search code examples
ruby-on-railsopensslpembackticksder

Convert DER key (with pass phrase) to PEM with ruby


I use this openssl command to convert a key file to pem:

openssl pkcs8 -inform DER -in LAN7008173R5.key -passin pass:12345678a -out converted_key.pem

And when i use cat converted_key.pem I get this (expected result):

-----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCC+8KIIUMVVphf ... kEGx50X8z7yLGNYY34YDPIU= -----END PRIVATE KEY-----

I'm trying to use backtick to run this command to save the private key value to a string to then save it to a file:

file = File.read(Rails.root.join('lib', 'cer', '2', 'LAN7008173R5.key'))

pem_key = openssl pkcs8 -inform DER -in #{file} -passin pass:12345678a

But I get this error (even though is the same file and route): ArgumentError: string contains null byte

Also when I do this:

OpenSSL::PKey::RSA.new(File.read(Rails.root.join('lib', 'cer', '2', 'LAN7008173R5.key')), '12345678a')

I get this: OpenSSL::PKey::RSAError: Neither PUB key nor PRIV key: nested asn1 error

I also tried this:

file = File.read(Rails.root.join('lib', 'cer', '2', 'LAN7008173R5.key'))

key = OpenSSL::PKey.read(file, '12345678a')

And got this: ArgumentError: Could not parse PKey: no start line

Thank you for your help!


Solution

  • I found it (didnt need 'read')!

    file = Rails.root.join('lib', 'cer', '2', 'LAN7008173R5.key')

    pem_key = openssl pkcs8 -inform DER -in #{file} -passin pass:12345678a

    And got my expected result:

    "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCC+8KIIUMVVphf\nvF1VGG... L80yqP3p6nXBohs45XsbF1\nkEGx50X8z7yLGNYY34YDPIU=\n-----END PRIVATE KEY-----\n"