如何使用x509.load_pem_x509_certificate()Python加密获取证书CommonName?

2024-09-25 18:21:47 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用Python cryptography库从客户端证书获取CommonName

如果使用pyOpenSSLssl,我使用:

import ssl
from OpenSSL import crypto

cert_raw = 'MIIGXDCCBUSgAwIBAgIJAMgCuv1aXz7l...base64 encoded`
cert_bytes = base64.b64decode(cert_raw)
cert_pem = ssl.DER_cert_to_PEM_cert(cert_bytes)
cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_pem)

从这里可以直接使用:

subject = cert.get_subject()
cn = subject.CN
print(cn)

thethings.com

但是我似乎找不到一种仅使用cryptography模块的快速方法来实现这一点。

我试过:

import ssl
from cryptography import x509

cert_raw = 'MIIGXDCCBUSgAwIBAgIJAMgCuv1aXz7l...base64 encoded`
cert_bytes = base64.b64decode(cert_raw)
cert_pem = ssl.DER_cert_to_PEM_cert(cert_bytes)
cert = x509.load_pem_x509_certificate(cert_pem.encode('ascii'), default_backend())

但最后会有一个字符串要拆分以获取CN。

我不相信CN会一直处于[0]的位置

subject = cert.subject

cn = subject.rfc4514_string()

cn_value = cn.split(',')[0].split('=')[1]

print(subject)
print(cn)
print(cn_value)

<Name(OU=Domain Control Validated,CN=thethings.com)>
CN=thethings.com,OU=Domain Control Validated
thethings.com

有没有更好的方法来使用cryptography模块实现这一点?


Tags: importcomsslcertrawbytescncrypto