2013-03-22 79 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