如何在python中获取证书颁发者信息? [英] How can i get Certificate issuer information in python?

查看:397
本文介绍了如何在python中获取证书颁发者信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望python证书中的签发信息。我尝试使用SSL和SSLSocket库,但没有发生。

I want the 'issued to' information from certificate in python. I try to use the SSL and SSLSocket library but did not happen.

推荐答案

更新后的答案

如果可以建立到远程服务器的连接,则可以使用 ssl 标准库模块:

If you can establish a connection to the remote server you can use the ssl standard library module:

import ssl, socket

hostname = 'google.com'
ctx = ssl.create_default_context()
with ctx.wrap_socket(socket.socket(), server_hostname=hostname) as s:
    s.connect((hostname, 443))
    cert = s.getpeercert()

subject = dict(x[0] for x in cert['subject'])
issued_to = subject['commonName']
issuer = dict(x[0] for x in cert['issuer'])
issued_by = issuer['commonName']

>>> issued_to
u'*.google.com'
>>> issued_by
u'Google Internet Authority G2'

原始答案

使用 pyOpenSSL

from OpenSSL import crypto

cert_file = '/path/to/your/certificate'
cert = crypto.load_certificate(crypto.FILETYPE_PEM, open(cert_file).read())
subject = cert.get_subject()
issued_to = subject.CN    # the Common Name field
issuer = cert.get_issuer()
issued_by = issuer.CN

您还可以访问其他组件,例如组织( subject.O / issuer.O ),组织单位( subject.OU / issuer.OU )。

You can also access additional components, e.g. organisation (subject.O/issuer.O), organisational unit (subject.OU/issuer.OU).

您的证书文件可能采用其他格式,因此您可以尝试使用 crypto.FILETYPE_ASN1 代替 crypto.FILETYPE_PEM

Your certificate file might be in another format, so you could try crypto.FILETYPE_ASN1 instead of crypto.FILETYPE_PEM.

这篇关于如何在python中获取证书颁发者信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆