Achal Sharma
Achal Sharma

Reputation: 152

Python: store Issuer CN value of X509 Certificate as a string

I am using the following code:

from cryptography import x509
from cryptography.hazmat.backends import default_backend
cert_info = x509.load_pem_x509_certificate(cert_pem, default_backend())
cert_issuer = cert_info.issuer

While debugging in PyCharm, I saw that the cert_issuer variable is as following:

cert_issuer

I want to store the commonName value in a variable. (value highlighted above)

I'm still fairly new to Python and was not able to find anything with these type of variables, can someone please guide me as to what should be the syntax to store that value in a variable.

Upvotes: 4

Views: 5036

Answers (1)

Topaco
Topaco

Reputation: 49251

The Common Name (CN) of the issuer can be determined as follows:

...
from cryptography.x509.oid import NameOID
cn = cert_info.issuer.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value
...

cryptography.x509.Certificate#issuer returns a cryptography.x509.Name object that contains a list of attributes. A particular attribute of this list can be accessed with get_attributes_for_oid(oid), where the name of the attribute has to be specified with an OID from cryptography.x509.oid.NameOID, e.g. COMMON_NAME. get_attributes_for_oid(oid) returns a list of cryptography.x509.NameAttributes objects. Since there is only one Issuer, the first NameAttribute object has to be used, whose value can be queried with value.

Upvotes: 9

Related Questions