2013-03-22 78 views
3

我的目標是開發一個Python腳本連接到主機,並確定在位類似於運行OpenSSL的服務器公共密鑰長度:提取公共密鑰長度

(openssl s_client -connect 10.18.254.29:443) 
yada yada yada 
Server certificate 
-----BEGIN CERTIFICATE----- 
-----END CERTIFICATE----- 
Server public key is 2048 bit 

我已經開始了這個基本的腳本:

from M2Crypto import SSL, RSA 
SSL.Connection.clientPostConnectionCheck = None 
ctx = SSL.Context() 
conn = SSL.Connection(ctx) 
conn.connect(('1.1.1.1', 443)) 
cert = conn.get_peer_cert() 
print cert.get_issuer().as_text() 

print cert.get_subject().as_text() 
print cert.get_fingerprint() 

print cert.get_pubkey().get_rsa().as_pem() 

我似乎無法找到一種方法來顯示密鑰的長度屬性。有任何想法嗎?

回答

2

的一般方法是:

print key.size() 

至於the docsPKey說,這是在字節,而不是位大小。所以,你想要得到的是「2048」,則需要8

如果你知道這是RSA,並已經呼籲get_rsa()倍增,你可以這樣做:

print len(rsa) 

The docs不要」不要說這是幹什麼的,但它會以位爲單位返回長度。

像往常一樣使用M2Crypto,你真正需要看的是libssl/libcrypto文檔(而不是openssl命令行工具)。而且,如果你不能猜測哪個C函數被調用,源代碼通常很簡單。

例如,你可以看到,PKey.size()是:

def size(self): 
    """ 
    Return the size of the key in bytes. 
    """ 
    return m2.pkey_size(self.pkey) 

而且RSA.__len__是:

def __len__(self): 
    return m2.rsa_size(self.rsa) << 3 

而且由內M2Crypto標準編碼約定,m2.rsa_size是圍繞RSA_size一大口包裝。

+0

是幫助了很多..... – user2200273 2013-03-22 19:11:54

1

基於從@abarnert我改變了我的代碼以下

from M2Crypto import SSL, RSA 

SSL.Connection.clientPostConnectionCheck = None 
ctx = SSL.Context() 
conn = SSL.Connection(ctx) 
conn.connect(('10.18.254.29', 443)) 
cert = conn.get_peer_cert() 

print cert.get_issuer().as_text() 

print cert.get_subject().as_text() 
print cert.get_fingerprint() 

**def size(self): 
    """ 
    Return the size of the key in bytes. 
    """ 
    return m2.pkey_size(self.pkey)** 

打印cert.get_pubkey()的幫助。大小()* 8