def extract_trust_anchors_from_xml(trust_anchor_xml):
"""Takes a bytestring with the XML from IANA; returns a list of trust anchors."""
# Turn the bytes from trust_anchor_xml into a string
trust_anchor_xml_string = bytes_to_string(trust_anchor_xml)
# Sanity check: make sure there is enough text in the returned stuff
if len(trust_anchor_xml_string) < 100:
die("The XML was too short: {} chars.".format(len(trust_anchor_xml_string)))
# ElementTree requries a file so use StringIO to turn the string into a file
try:
trust_anchor_as_file = StringIO(trust_anchor_xml_string) # This works for Python 3
except:
trust_anchor_as_file = StringIO(unicode(trust_anchor_xml_string)) # Needed for Python 2
# Get the tree
trust_anchor_tree = xml.etree.ElementTree.ElementTree(file=trust_anchor_as_file)
# Get all the KeyDigest elements
digest_elements = trust_anchor_tree.findall(".//KeyDigest")
print("There were {} KeyDigest elements in the trust anchor file.".format(\
len(digest_elements)))
trust_anchors = [] # Global list of dicts that is taken from the XML file
# Collect the values for the KeyDigest subelements and attributes
for (count, this_digest_element) in enumerate(digest_elements):
digest_value_dict = {}
for this_subelement in ["KeyTag", "Algorithm", "DigestType", "Digest"]:
try:
this_key_tag_text = (this_digest_element.find(this_subelement)).text
except:
die("Did not find {} element in a KeyDigest in a trust anchor.".format(\
this_subelement))
digest_value_dict[this_subelement] = this_key_tag_text
for this_attribute in ["validFrom", "validUntil"]:
if this_attribute in this_digest_element.keys():
digest_value_dict[this_attribute] = this_digest_element.attrib[this_attribute]
else:
digest_value_dict[this_attribute] = "" # Missing attributes get empty values
# Save this to the global trust_anchors list
print("Added the trust anchor {} to the list:\n{}".format(count, pprint.pformat(\
digest_value_dict)))
trust_anchors.append(digest_value_dict)
if len(trust_anchors) == 0:
die("There were no trust anchors found in the XML file.")
return trust_anchors
评论列表
文章目录