2010-07-01 193 views

回答

28

如果你使用ssh-凱基生成密鑰:

$ ssh-keygen 

然後,你可以使用OpenSSL拔出公鑰和寫在DER格式是這樣的:

$ openssl rsa -in id_rsa -out pub.der -outform DER -pubout 
writing RSA key 

您可以查看DER輸出PEM像這樣:

$ openssl rsa -in pub.der -inform DER -pubin -text 

我不使用Ruby,所以我不知道它是多麼容易使用來自Ruby的OpenSSL。

編輯:我回答得太快 - 你寫了id_rsa.pub,你可能沒有id_rsa本身。另一個堆棧溢出問題是用於反向轉換,但在那裏找到的源代碼可能有幫助: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 } 

可以在外殼與這些OpenSSL的命令檢查輸出:

$ openssl rsa -pubin -text -in id_rsa.pem 
$ openssl rsa -pubin -text -inform DER -in id_rsa.der 
+0

好的解決方案,謝謝! – 2010-07-02 20:37:26

2

如果您只能訪問通過SSH-凱基生成的公鑰,並希望將其轉換爲DER格式,以下工作:

ssh-keygen -f id_rsa.pub -e -m PKCS8 | openssl pkey -pubin -outform DER

氏s首先使用ssh-keygen將密鑰轉換爲PKCS8 PEM格式,然後使用openssl pkey將其轉換爲DER格式。

(這與Jim Flood的答案完成相同的事情,但未觸及私鑰文件。)

+0

他說*「如何以編程方式將id_rsa.pub文件轉換爲RSA DER格式化的密鑰?」*。他沒有要求命令去做。 – jww 2015-05-27 18:54:01

+0

另外,不適用於所有發行版 – 2016-04-20 06:39:31