Python:检索<objectidentifier>

时间:2019-02-27 17:04:22

标签: python cryptography

我正在使用加密技术加载新证书并检索其属性。

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

最后两个将结果打印为:

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')>])>

如何正确访问这些属性之一? 例如,我只想打印sha256WithRSAEncryption,只打印C=GR, O=MyTrust, CN=MyTrust

丹妮尔(Danielle)回答后,我正在更新问题。

>>> 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']

当我打印一张时,仍然很难访问:

>>> 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')>])>]}

如何获取所有值? 国家的名字 机构名称 organizationUnitName commonName 等

2 个答案:

答案 0 :(得分:1)

如果要检查对象并找到其属性,请尝试使用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

答案 1 :(得分:0)

对于问题的第二部分,我在这里写下答案。

>>> cert.issuer
>>> for attribute in cert.issuer:
... print(attribute.oid._name)
... print(attribute.value)

countryName
GR
stateOrProvinceName
Blah
localityName
Blah
organizationName
MyTrust
organizationalUnitName
MyTrust
commonName
MyTrust

感谢Danielle,让我对函数有了更深入的了解:dir()!!!