python - 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
解决方案
如果你想检查一个对象并找到它的属性,试试这个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
推荐阅读
- android - Android ImageButton 中的圆角不起作用
- python - 使用熊猫将多数据类型数据帧转换为python中的整数编码数据帧
- javascript - 如何测试现有的 Angularjs 整体性能(DOM 渲染)?
- java - 如何使用 Nashorn 引擎调用 Java 对象
- javascript - 操作 Array.map 中的前一项?
- c++ - QString替换引号外的字符
- c# - 将类从 C++ 转换为 C#
- ios - 注释的重用标识符有什么意义
- c# - 如何将 .NET 类库作为 Web 服务运行
- python - Pykafka - 异步发送消息和接收确认