【发布时间】:2011-03-10 21:09:58
【问题描述】:
我有 ssh-keygen 生成的 id_rsa.pub 密钥。 如何以编程方式将 id_rsa.pub 文件转换为 RSA DER 格式的密钥?
【问题讨论】:
我有 ssh-keygen 生成的 id_rsa.pub 密钥。 如何以编程方式将 id_rsa.pub 文件转换为 RSA DER 格式的密钥?
【问题讨论】:
如果使用 ssh-keygen 生成密钥:
$ ssh-keygen
然后你可以使用 openssl 来提取公钥并将其写入 DER 格式,如下所示:
$ openssl rsa -in id_rsa -out pub.der -outform DER -pubout
writing RSA key
您可以像这样以 PEM 形式查看 DER 输出:
$ openssl rsa -in pub.der -inform DER -pubin -text
我不使用 Ruby,所以我不知道从 Ruby 中使用 OpenSSL 有多容易。
编辑:我回答得太快了——你写了 id_rsa.pub 并且你可能没有 id_rsa 本身。另一个 Stack Overflow 问题是关于反向转换的,但在那里找到的源代码可能会有所帮助:Convert pem key to ssh-rsa format 拥有 PEM 后,您可以使用 openssl 将 PEM 转换为 DER。
编辑,2014 年 5 月:Ruby 已成为我最喜欢的编程语言,最初的问题(自编辑后)询问了 Ruby。下面是读取 id_rsa.pub(公钥)并编写 OpenSSL 生成的 DER 格式公钥的代码:
require 'openssl'
require 'base64'
def read_length(s)
# four bytes, big-endian
length = s[0..3].unpack('N')[0]
end
def read_integer(s, length)
# shift all bytes into one integer
s[4..3 + length].unpack('C*').inject { |n, b| (n << 8) + b }
end
def cut(s, length)
s[4 + length..-1]
end
def decode_pub(pub)
# the second field is the Base64 piece needed
s = Base64.decode64(pub.split[1])
# first field reading "ssh-rsa" is ignored
i = read_length(s)
s = cut(s, i)
# public exponent e
i = read_length(s)
e = read_integer(s, i)
s = cut(s, i)
# modulus n
i = read_length(s)
n = read_integer(s, i)
[ e, n ]
end
def make_asn1(e, n)
# Simple RSA public key in ASN.1
e0 = OpenSSL::ASN1::Integer.new(e)
n1 = OpenSSL::ASN1::Integer.new(n)
OpenSSL::ASN1::Sequence.new([ e0, n1 ])
end
pub = File.read('id_rsa.pub')
asn1 = make_asn1(*decode_pub(pub))
# Let OpenSSL deal with converting from the simple ASN.1
key = OpenSSL::PKey::RSA.new(asn1.to_der)
# Write out the public key in both PEM and DER formats
File.open('id_rsa.pem', 'w') { |f| f.write key.to_pem }
File.open('id_rsa.der', 'w') { |f| f.write key.to_der }
您可以在 shell 中使用以下 openssl 命令检查输出:
$ openssl rsa -pubin -text -in id_rsa.pem
$ openssl rsa -pubin -text -inform DER -in id_rsa.der
【讨论】:
如果您只能访问 ssh-keygen 生成的公钥,并且想将其转换为 DER 格式,则可以使用以下方法:
ssh-keygen -f id_rsa.pub -e -m PKCS8 | openssl pkey -pubin -outform DER
这首先使用ssh-keygen 将密钥转换为PKCS8 PEM 格式,然后使用openssl pkey 将其转换为DER 格式。
(这完成了与 Jim Flood 的回答相同的事情,但没有触及私钥文件。)
【讨论】: