将 PKCS#8 二进制密钥加载到 Ruby 中 [英] Load PKCS#8 binary key into Ruby
问题描述
我正在尝试将以二进制 DER
格式 (PKCS#8
) 编码的特定私钥加载到 Ruby 中.
I'm trying to load a particular private key encoded in binary DER
format (PKCS#8
) into Ruby.
然而,OpenSSL::PKey
不会识别它.我可以通过做一些控制台工作并将其转换为 PEM
来使其工作,如下所示:
However, OpenSSL::PKey
won't recognize it. I can make it work by doing some console work and transforming it into a PEM
like so:
openssl pkcs8 -inform DER -in file.key -passin pass:xxxxxxxx >private_key.pem
此后,即可正确读取密钥.
After this, the key can correctly be read.
但是,因为我希望整个过程在内存中完成,而不是写入和读取文件.
However, since I would like for the whole process to be done in memory instead of writing and reading files.
所以我的问题是:是否可以将二进制编码的 DER
格式的私钥加载到 Ruby/OpenSSL 中?
So my question is: Is it possible to load private keys from the binary encoded DER
format into Ruby/OpenSSL?
感谢您的时间,
费尔南多
推荐答案
是的,您可以间接使用 Ruby OpenSSL 加载 PKCS#8 DER 编码的私钥.
Yes, you can indirectly load PKCS#8 DER-encoded private keys using Ruby OpenSSL.
OpenSSL::PKey::RSA.new
只会处理 PEM 格式的 PKCS#8,但很容易读取二进制 DER 并将其转换为 PEM 格式的字符串然后加载来自字符串.
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.
例如,使用这些 DER 编码的私钥:
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
你可以这样做:
require 'openssl'
require 'base64'
def box(tag, lines)
lines.unshift "-----BEGIN #{tag}-----"
lines.push "-----END #{tag}-----"
lines.join("
")
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')
读取 DER 字节,Base64 并将 PEM 标签放在顶部和底部,然后加载密钥.
Read the DER bytes, Base64 them and put the PEM tags on top and bottom, and then load the key.
这篇关于将 PKCS#8 二进制密钥加载到 Ruby 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!