首页 > 解决方案 > Python: retrieve attribute of

问题描述

I am using cryptography to load a new certificate and retrieve its attributes.

from cryptography import x509
from cryptography.hazmat.backends import default_backend
path = "mycert.crt"
with open(path, 'rb') as cert_file:
    data = cert_file.read()
cert = x509.load_pem_x509_certificate(data, default_backend())
sign = cert.signature_algorithm_oid
iss = cert.issuer

The last two print the result as:

print sign
<ObjectIdentifier(oid=1.1.1.1.1.1.11, name=sha256WithRSAEncryption)>

print iss
<Name([<NameAttribute(oid=<ObjectIdentifier(oid=1.1.1.1, name=countryName)>, value=u'GR')>, <NameAttribute(oid=<ObjectIdentifier(oid=1.1.1.1, name=organizationName)>, value=u'MyTrust')>, <NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.3, name=commonName)>, value=u'MyTrust')>])>

How can I properly access one of those attributes? For example, I want to print only the sha256WithRSAEncryption and only the C=GR, O=MyTrust, CN=MyTrust

After Danielle's response, I am updating the question.

>>> dir(iss)   
>>> ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__len__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_attributes', 'get_attributes_for_oid', 'public_bytes', 'rdns']

And when I print one it is still difficult to access:

>>> print(iss.__dict__)  
>>> {'_attributes': [<RelativeDistinguishedName([<NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.6, name=countryName)>, value=u'GR')>])>, <RelativeDistinguishedName([<NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.10, name=organizationName)>, value=u'MyTrust')>])>, <RelativeDistinguishedName([<NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.11, name=organizationalUnitName)>, value=u'MyTrust')>])>, <RelativeDistinguishedName([<NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.3, name=commonName)>, value=u'MyTrust')>])>]}

How can I get all the values? countryName organizationName organizationalUnitName commonName etc

标签: pythoncryptography

解决方案


如果你想检查一个对象并找到它的属性,试试这个dir()函数:

>>> dir(sign)
>>> ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_dotted_string', '_name', 'dotted_string']

也许_name

>>> print(sign._name)
>>> sha1WithRSAEncryption

https://docs.python.org/2/library/functions.html#dir


推荐阅读