【问题标题】:Extract public key length in bits提取公钥长度(以位为单位)
【发布时间】:2013-03-22 18:00:45
【问题描述】:

我的目标是开发一个 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()

我似乎找不到显示密钥长度属性的方法。有什么想法吗?

【问题讨论】:

    标签: python m2crypto


    【解决方案1】:

    一般的方式是:

    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_sizeRSA_size 的 SWIG 包装器。

    【讨论】:

      【解决方案2】:

      根据@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().size()*8

      【讨论】:

        猜你喜欢
        • 2014-04-25
        • 2010-11-02
        • 2013-01-11
        • 1970-01-01
        • 1970-01-01
        • 2011-09-24
        • 2010-09-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多