Load PKCS#8 binary key into Ruby

廉价感情. 提交于 2019-11-28 13:31:14

Yes, you can indirectly load PKCS#8 DER-encoded private keys using Ruby OpenSSL.

OpenSSL::PKey::RSA.new will only handle PEM-formatted PKCS#8, but it is easy to read the binary DER and convert it to a PEM-formatted string and then load from the string.

For example, with these DER-encoded private keys:

$ openssl genrsa | openssl pkcs8 -topk8 -outform DER \
    -nocrypt -out pkcs8.key
$ openssl genrsa | openssl pkcs8 -topk8 -outform DER \
    -v2 des3 -passout pass:secret -out pkcs8_des3.key

You can do something like this:

require 'openssl'
require 'base64'

def box(tag, lines)
  lines.unshift "-----BEGIN #{tag}-----"
  lines.push "-----END #{tag}-----"
  lines.join("\n")
end

def der_to_pem(tag, der)
  box tag, Base64.strict_encode64(der).scan(/.{1,64}/)
end

pem = der_to_pem('PRIVATE KEY', File.read('pkcs8.key'))
key = OpenSSL::PKey::RSA.new(pem)

pem2 = der_to_pem('ENCRYPTED PRIVATE KEY', File.read('pkcs8_des3.key'))
key2 = OpenSSL::PKey::RSA.new(pem2, 'secret')

Read the DER bytes, Base64 them and put the PEM tags on top and bottom, and then load the key.

Certificate is capable of handling DER-encoded certificates and certificates encoded in OpenSSL's PEM format.

You could find documentation about OpenSSL implementation for Ruby here :

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!