简单的DER Cert在python中解析

Dav*_*d A 5 python ssl-certificate public-key

哪个是用python解析带有X509证书的二进制文件以DER格式提取公钥的最佳方法.

De1*_*117 10

上述答案有些陈旧(截至2017年).

您可以使用asn1crypto以更好的方式执行此操作:

from asn1crypto.x509 import Certificate

with open("mycert.der", "rb") as f:
    cert = Certificate.load(f.read())

n = cert.public_key.native["public_key"]["modulus"]
e = cert.public_key.native["public_key"]["public_exponent"]

print("{:#x}".format(n))    # prints the modulus (hexadecimal)
print("{:#x}".format(e))    # same, for the public exponent
Run Code Online (Sandbox Code Playgroud)

它相对较新(从我可以看到,2015年中),提供了比已经提到的库更好的界面,并且比pyasn1作者更快.


小智 8

Python的内置SSL模块和PyOpenSSL都没有API来提取私钥并访问其信息.M2Crypto不再维护,不适用于OpenSSL 1.0及更新版本.

PyOpenSSL有一个公钥类,但其功能有限:

>>> with open("cert.der", "rb") as f:
...     der = f.read()
... 
>>> import OpenSSL.crypto
>>> x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, der)
>>> pkey = x509.get_pubkey()
>>> dir(pkey)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'bits', 'check', 'generate_key', 'type']
>>> pkey.bits()
4096L
>>> pkey.type() == OpenSSL.crypto.TYPE_RSA
True
Run Code Online (Sandbox Code Playgroud)

Python 3.4可能会获得一个X509类型,可以公开更多信息,如SPKI.


Dav*_*d A 5

自从我问这个问题以来已经很长时间了,尽管由于浏览量的原因,我想描述一下我是如何设法让它发挥作用的。

通过使用 OpenSSL API,我们可以轻松地以易于阅读的方式打印 DER 证书。尽管它的功能非常有限,但这只是一个例子。

print OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_TEXT,x509)
Run Code Online (Sandbox Code Playgroud)

但是,我想直接控制 var 中的键(需要将其发送到其他函数),为了做到这一点,我做了以下函数

def parse_asn1_der(derfile):
    from pyasn1_modules import  rfc2437,rfc2459
    from pyasn1.codec.der import decoder
    certType = rfc2459.Certificate(); 
    raw=derfile #the result of open(fname,"rb").read()
    cert,rest = decoder.decode(raw, asn1Spec=certType)
    RSAKEYSDATA=frombits(cert.getComponentByName("tbsCertificate").getComponentByName("subjectPublicKeyInfo").getComponentByName("subjectPublicKey"))
    SignatureCert=frombits(cert.getComponentByName("signatureValue")).encode("hex")
    rsaType=rfc2437.RSAPublicKey();
    rsadata,rsadata_rest = decoder.decode(RSAKEYSDATA, asn1Spec=rsaType)
    print "----"
    print "Certificate Plain Data"
    print "RSA Modulus: %X" %rsadata.getComponentByName("modulus")
    print "RSA Public exponent: %X" %rsadata.getComponentByName("publicExponent")
    print "Signature: %s"%SignatureCert
    return rsadata.getComponentByName("modulus")
Run Code Online (Sandbox Code Playgroud)

希望它能帮助任何环顾四周的人。