Both methods of parsing the digital certificate -openssl command module and python pyopenssl

This article describes two ways to get a digital certificate file useful information.

There are several certificate file formats, including cer, der, crt, pem and so on. For these file formats can usually use openssl to view information and outputs. Meanwhile openssl command system comes with tools generally, more convenient to use. E.g. .cer certificate parsing the openssl command follows:

openssl x509 -inform DER -in xxx.cer -noout -subject

The command outputs certificate subject information, as follows:

subject= /C=CN/ST=ZheJiang/L=HangZhou/O=Alibaba (China) Technology Co., Ltd./CN=*.cnzz.com

However, the use of the process found, the command can only provide openssl resolve issuer and subject to this level, then finer granularity can not be extracted directly, for example, which can not be directly extracted O. If you want to direct output suject of O, you must be a regular match, the command is as follows:
openssl x509 -inform DER -in xxx.cer -noout -subject | grep -oP "(?<=/O=).+?(?=/CN=)"

Output can be obtained as follows:

Alibaba (China) Technology Co., Ltd.

If you need to extract as CN or L ST and some other fields also need to write a number of regular match. At the same time you can see the output of the subject if there OU and other output, the relevant order should be noted, also need to pay attention to write regular, very inconvenient.

Since python provides support for openssl, so you can use the module in python to get the certificate information.

The module is installed Command:pip install pyopenssl

Extraction demo as follows:

def getCertSubjectInfo(certName):
    from OpenSSL import crypto
    cert = crypto.load_certificate(crypto.FILETYPE_ASN1, open(certName).read()) 
    subject = cert.get_subject() 
    certSubjectInfo = []
    certSubjectInfo.append(subject.O)
    certSubjectInfo.append(subject.C)
    certSubjectInfo.append(subject.L)
    certSubjectInfo.append(subject.ST)
    certSubjectInfo.append(subject.CN)
    certSubjectInfo.append(subject.OU)
    # 得到证书颁发机构 
    #issuer = cert.get_issuer() 
    #issued_by = issuer.CN
    if subject.O != None:
        print(subject.O)
    return certSubjectInfo

Wherein the type comprising a certificate load_certificate FILETYPE_PEM, FILETYPE_ASN1 two kinds can be selected depending on the type of certificate. API reference, see here

You can see can be extracted directly extracted directly subject of O, CN and many other information through the python program, more convenient than the command openssl.

This article CSDN village teenager original article, reprinted remember even with a small tail, bloggers link here .

发布了132 篇原创文章 · 获赞 183 · 访问量 28万+

Guess you like

Origin blog.csdn.net/javajiawei/article/details/95617550