How do I get the CommonName from a client certificate using the Python cryptography library?
If using pyOpenSSL and ssl, I use:
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)
From there it's straightforward to use:
subject = cert.get_subject()
cn = subject.CN
print(cn)
thethings.com
But I can't seem to find a quick way to do this with the cryptography module alone.
I've tried:
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())
But end up with a string to split in order to get CN.
I'm not confident that CN will always be in position [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
Is there a better way to do this with the cryptography module?