Python elementtree find function reads Signature as empty (None)

你说的曾经没有我的故事 提交于 2019-12-12 04:35:59

问题


I'm trying to read Signature, SignatureValue and SignedInfo from signed XML in Python with ElementTree but it reads as None. Other xml attributes are read fine. How can I read Signature, SignatureValue and SignedInfo?

Here's my code snippet:

xml_file = open(settings.STATIC_ROOT + '/file/test.xml', 'rt').read()
response_xml = xml_et.fromstring(xml_file.encode('utf-8'))
print response_xml.find('Signature')  # prints None
print response_xml.find('SignatureValue')  # prints None
print response_xml.find('SignedInfo')  # prints None
print response_xml.find('OrderID').text  # works fine

Here's my test XML:

<?xml version="1.0" encoding="UTF-8"?>
<Message date="08/09/2016 06:47:20">
   <Version>1.0</Version>
   <OrderID>ABCD:123456</OrderID>
   <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
      <SignedInfo>
         <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
         <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
         <Reference URI="">
            <Transforms>
               <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
               <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
            </Transforms>
            <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
            <DigestValue>blabla=</DigestValue>
         </Reference>
      </SignedInfo>
      <SignatureValue>blabla==</SignatureValue>
      <KeyInfo>
         <KeyName>Public key of certificate</KeyName>
         <KeyValue>
            <RSAKeyValue>
               <Modulus>blabla==</Modulus>
               <Exponent>AQAB</Exponent>
            </RSAKeyValue>
         </KeyValue>
         <X509Data>
            <X509Certificate>blabla</X509Certificate>
         </X509Data>
      </KeyInfo>
   </Signature>
</Message>

回答1:


Its because you have namespace on the Signature element, what you can do is find the element with the namespace

print response_xml.find('{http://www.w3.org/2000/09/xmldsig#}Signature')

then you will have to take the signature element and find all sub elements from it

something like this:

namespace = "{http://www.w3.org/2000/09/xmldsig#}"
signature_elem = response_xml.find(namespace +'Signature')
print signature_elem
print signature_elem.find(namespace+'SignatureValue')
print signature_elem.find(namespace+'SignedInfo')


来源:https://stackoverflow.com/questions/43451194/python-elementtree-find-function-reads-signature-as-empty-none

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!