internal static CanonicalXmlNodeList GetPropagatedAttributes(XmlElement elem) { if (elem == null) { return(null); } CanonicalXmlNodeList list = new CanonicalXmlNodeList(); XmlNode parentNode = elem; if (parentNode == null) { return(null); } bool flag = true; while (parentNode != null) { XmlElement element = parentNode as XmlElement; if (element == null) { parentNode = parentNode.ParentNode; } else { if (!IsCommittedNamespace(element, element.Prefix, element.NamespaceURI) && !IsRedundantNamespace(element, element.Prefix, element.NamespaceURI)) { string name = (element.Prefix.Length > 0) ? ("xmlns:" + element.Prefix) : "xmlns"; XmlAttribute attribute = elem.OwnerDocument.CreateAttribute(name); attribute.Value = element.NamespaceURI; list.Add(attribute); } if (element.HasAttributes) { foreach (XmlAttribute attribute2 in element.Attributes) { if (flag && (attribute2.LocalName == "xmlns")) { XmlAttribute attribute3 = elem.OwnerDocument.CreateAttribute("xmlns"); attribute3.Value = attribute2.Value; list.Add(attribute3); flag = false; } else if ((attribute2.Prefix == "xmlns") || (attribute2.Prefix == "xml")) { list.Add(attribute2); } else if (((attribute2.NamespaceURI.Length > 0) && !IsCommittedNamespace(element, attribute2.Prefix, attribute2.NamespaceURI)) && !IsRedundantNamespace(element, attribute2.Prefix, attribute2.NamespaceURI)) { string str2 = (attribute2.Prefix.Length > 0) ? ("xmlns:" + attribute2.Prefix) : "xmlns"; XmlAttribute attribute4 = elem.OwnerDocument.CreateAttribute(str2); attribute4.Value = attribute2.NamespaceURI; list.Add(attribute4); } } } parentNode = parentNode.ParentNode; } } return(list); }
public override object GetOutput() { CanonicalXmlNodeList list = new CanonicalXmlNodeList(); if (!string.IsNullOrEmpty(this._xpathexpr)) { XPathNavigator navigator = this._document.CreateNavigator(); XPathNodeIterator iterator = navigator.Select("//. | //@*"); XPathExpression expr = navigator.Compile("boolean(" + this._xpathexpr + ")"); expr.SetContext(this._nsm); while (iterator.MoveNext()) { XmlNode node = ((IHasXmlNode) iterator.Current).GetNode(); if ((bool) iterator.Current.Evaluate(expr)) { list.Add(node); } } iterator = navigator.Select("//namespace::*"); while (iterator.MoveNext()) { XmlNode node2 = ((IHasXmlNode) iterator.Current).GetNode(); list.Add(node2); } } return list; }
public override object GetOutput() { CanonicalXmlNodeList resultNodeList = new CanonicalXmlNodeList(); if (!string.IsNullOrEmpty(_xpathexpr)) { XPathNavigator navigator = _document.CreateNavigator(); XPathNodeIterator it = navigator.Select("//. | //@*"); XPathExpression xpathExpr = navigator.Compile("boolean(" + _xpathexpr + ")"); xpathExpr.SetContext(_nsm); while (it.MoveNext()) { XmlNode node = ((IHasXmlNode)it.Current).GetNode(); bool include = (bool)it.Current.Evaluate(xpathExpr); if (include == true) { resultNodeList.Add(node); } } // keep namespaces it = navigator.Select("//namespace::*"); while (it.MoveNext()) { XmlNode node = ((IHasXmlNode)it.Current).GetNode(); resultNodeList.Add(node); } } return(resultNodeList); }
public override object GetOutput() { CanonicalXmlNodeList list = new CanonicalXmlNodeList(); if (!string.IsNullOrEmpty(this._xpathexpr)) { XPathNavigator navigator = this._document.CreateNavigator(); XPathNodeIterator iterator = navigator.Select("//. | //@*"); XPathExpression expr = navigator.Compile("boolean(" + this._xpathexpr + ")"); expr.SetContext(this._nsm); while (iterator.MoveNext()) { XmlNode node = ((IHasXmlNode)iterator.Current).GetNode(); if ((bool)iterator.Current.Evaluate(expr)) { list.Add(node); } } iterator = navigator.Select("//namespace::*"); while (iterator.MoveNext()) { XmlNode node2 = ((IHasXmlNode)iterator.Current).GetNode(); list.Add(node2); } } return(list); }
/// <include file='doc\Transform.uex' path='docs/doc[@for="XmlDsigXPathTransform.GetOutput"]/*' /> public override Object GetOutput() { CanonicalXmlNodeList resultNodeList = new CanonicalXmlNodeList(); foreach (XmlNode node in _inputNodeList) { if (node == null) { continue; } // keep namespaces if (node is XmlAttribute && (node.LocalName == "xmlns" || node.Prefix == "xmlns")) { resultNodeList.Add(node); continue; } try { XmlNode result = node.SelectSingleNode(_xpathexpr, _nsm); if (result != null) { resultNodeList.Add(node); } } catch { #if _DEBUG if (debug) { Console.WriteLine(node.OuterXml); } #endif } } return(resultNodeList); }
private byte[] GetC14NDigest(HashAlgorithm hash) { if (!_bCacheValid || !SignedInfo.CacheValid) { string baseUri = (_containingDocument == null ? null : _containingDocument.BaseURI); XmlResolver resolver = (_bResolverSet ? _xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); XmlDocument doc = Utils.PreProcessElementInput(SignedInfo.GetXml(), resolver, baseUri); // Add non default namespaces in scope CanonicalXmlNodeList namespaces = (_context == null ? null : Utils.GetPropagatedAttributes(_context)); SignedXmlDebugLog.LogNamespacePropagation(this, namespaces); Utils.AddNamespaces(doc.DocumentElement, namespaces); Transform c14nMethodTransform = SignedInfo.CanonicalizationMethodObject; c14nMethodTransform.Resolver = resolver; c14nMethodTransform.BaseURI = baseUri; SignedXmlDebugLog.LogBeginCanonicalization(this, c14nMethodTransform); c14nMethodTransform.LoadInput(doc); SignedXmlDebugLog.LogCanonicalizedOutput(this, c14nMethodTransform); _digestedSignedInfo = c14nMethodTransform.GetDigestedOutput(hash); _bCacheValid = true; } return(_digestedSignedInfo); }
private static void MarkInclusionStateForNodes(XmlNodeList nodeList, XmlDocument inputRoot, XmlDocument root) { CanonicalXmlNodeList elementList = new CanonicalXmlNodeList(); CanonicalXmlNodeList elementListCanonical = new CanonicalXmlNodeList(); elementList.Add(inputRoot); elementListCanonical.Add(root); int index = 0; do { XmlNode currentNode = (XmlNode) elementList[index]; XmlNode currentNodeCanonical = (XmlNode) elementListCanonical[index]; XmlNodeList childNodes = currentNode.ChildNodes; XmlNodeList childNodesCanonical = currentNodeCanonical.ChildNodes; for (int i = 0; i < childNodes.Count; i++) { elementList.Add(childNodes[i]); elementListCanonical.Add(childNodesCanonical[i]); if (Utils.NodeInList(childNodes[i], nodeList)) { MarkNodeAsIncluded(childNodesCanonical[i]); } XmlAttributeCollection attribNodes = childNodes[i].Attributes; if (attribNodes != null) { for (int j = 0; j < attribNodes.Count; j++) { if (Utils.NodeInList(attribNodes[j], nodeList)) { MarkNodeAsIncluded(childNodesCanonical[i].Attributes.Item(j)); } } } } index++; } while (index < elementList.Count); }
internal static XmlNodeList AllDescendantNodes(XmlNode node, bool includeComments) { CanonicalXmlNodeList nodeList = new CanonicalXmlNodeList(); CanonicalXmlNodeList elementList = new CanonicalXmlNodeList(); CanonicalXmlNodeList attribList = new CanonicalXmlNodeList(); CanonicalXmlNodeList namespaceList = new CanonicalXmlNodeList(); int index = 0; elementList.Add(node); do { XmlNode rootNode = (XmlNode)elementList[index]; // Add the children nodes XmlNodeList childNodes = rootNode.ChildNodes; if (childNodes != null) { foreach (XmlNode node1 in childNodes) { if (includeComments || (!(node1 is XmlComment))) { elementList.Add(node1); } } } // Add the attribute nodes XmlAttributeCollection attribNodes = rootNode.Attributes; if (attribNodes != null) { foreach (XmlNode attribNode in rootNode.Attributes) { if (attribNode.LocalName == "xmlns" || attribNode.Prefix == "xmlns") { namespaceList.Add(attribNode); } else { attribList.Add(attribNode); } } } index++; } while (index < elementList.Count); foreach (XmlNode elementNode in elementList) { nodeList.Add(elementNode); } foreach (XmlNode attribNode in attribList) { nodeList.Add(attribNode); } foreach (XmlNode namespaceNode in namespaceList) { nodeList.Add(namespaceNode); } return(nodeList); }
//-------------------------- Constructors --------------------------- /// <include file='doc\SignedXml.uex' path='docs/doc[@for="SignedXml.SignedXml"]/*' /> public SignedXml() { m_containingDocument = null; m_parentElement = null; m_namespaces = null; m_signature = new Signature(); m_signature.SignedInfo = new SignedInfo(); m_signingKey = null; }
public DataObject (string id, string mimeType, string encoding, XmlElement data) { if (data == null) throw new ArgumentNullException("data"); m_id = id; m_mimeType = mimeType; m_encoding = encoding; m_elData = new CanonicalXmlNodeList(); m_elData.Add(data); m_cachedXml = null; }
internal static XmlNodeList AllDescendantNodes(XmlNode node, bool includeComments) { CanonicalXmlNodeList list = new CanonicalXmlNodeList(); CanonicalXmlNodeList list2 = new CanonicalXmlNodeList(); CanonicalXmlNodeList list3 = new CanonicalXmlNodeList(); CanonicalXmlNodeList list4 = new CanonicalXmlNodeList(); int num = 0; list2.Add(node); do { XmlNode node2 = list2[num]; XmlNodeList childNodes = node2.ChildNodes; if (childNodes != null) { foreach (XmlNode node3 in childNodes) { if (includeComments || !(node3 is XmlComment)) { list2.Add(node3); } } } if (node2.Attributes != null) { foreach (XmlNode node4 in node2.Attributes) { if ((node4.LocalName == "xmlns") || (node4.Prefix == "xmlns")) { list4.Add(node4); } else { list3.Add(node4); } } } num++; }while (num < list2.Count); foreach (XmlNode node5 in list2) { list.Add(node5); } foreach (XmlNode node6 in list3) { list.Add(node6); } foreach (XmlNode node7 in list4) { list.Add(node7); } return(list); }
internal static XmlNodeList AllDescendantNodes(XmlNode node, bool includeComments) { CanonicalXmlNodeList list = new CanonicalXmlNodeList(); CanonicalXmlNodeList list2 = new CanonicalXmlNodeList(); CanonicalXmlNodeList list3 = new CanonicalXmlNodeList(); CanonicalXmlNodeList list4 = new CanonicalXmlNodeList(); int num = 0; list2.Add(node); do { XmlNode node2 = list2[num]; XmlNodeList childNodes = node2.ChildNodes; if (childNodes != null) { foreach (XmlNode node3 in childNodes) { if (includeComments || !(node3 is XmlComment)) { list2.Add(node3); } } } if (node2.Attributes != null) { foreach (XmlNode node4 in node2.Attributes) { if ((node4.LocalName == "xmlns") || (node4.Prefix == "xmlns")) { list4.Add(node4); } else { list3.Add(node4); } } } num++; } while (num < list2.Count); foreach (XmlNode node5 in list2) { list.Add(node5); } foreach (XmlNode node6 in list3) { list.Add(node6); } foreach (XmlNode node7 in list4) { list.Add(node7); } return list; }
public DataObject(string id, string mimeType, string encoding, XmlElement data) { if (data == null) { throw new ArgumentNullException("data"); } this.m_id = id; this.m_mimeType = mimeType; this.m_encoding = encoding; this.m_elData = new CanonicalXmlNodeList(); this.m_elData.Add(data); this.m_cachedXml = null; }
/// <include file='doc\DataObject.uex' path='docs/doc[@for="DataObject.DataObject1"]/*' /> public DataObject(String id, String mimeType, String encoding, XmlElement data) { if (data == null) { throw new ArgumentNullException("data"); } m_strId = id; m_strMimeType = mimeType; m_strEncoding = encoding; m_elData = new CanonicalXmlNodeList(); m_elData.Add(data); m_cachedXml = null; }
/// <include file='doc\SignedXml.uex' path='docs/doc[@for="SignedXml.SignedXml2"]/*' /> public SignedXml(XmlElement elem) { if (elem == null) { throw new ArgumentNullException("elem"); } m_containingDocument = elem.OwnerDocument; m_parentElement = elem; m_namespaces = GetPropagatedAttributes(m_parentElement); m_signature = new Signature(); m_signature.SignedInfo = new SignedInfo(); m_signingKey = null; }
/// <include file='doc\SignedXml.uex' path='docs/doc[@for="SignedXml.SignedXml1"]/*' /> public SignedXml(XmlDocument document) { if (document == null) { throw new ArgumentNullException("document"); } m_containingDocument = document; m_parentElement = document.DocumentElement; m_namespaces = GetPropagatedAttributes(m_parentElement); m_signature = new Signature(); m_signature.SignedInfo = new SignedInfo(); m_signingKey = null; }
public DataObject(string id, string mimeType, string encoding, XmlElement data) { if (data is null) { throw new ArgumentNullException(nameof(data)); } _id = id; _mimeType = mimeType; _encoding = encoding; _elData = new CanonicalXmlNodeList(); _elData.Add(data); _cachedXml = null; }
private void BuildDigestedReferences() { // Default the DigestMethod and Canonicalization Reference reference = m_signature.Reference; CanonicalXmlNodeList nodeList = new CanonicalXmlNodeList(); // If no DigestMethod has yet been set, default it to sha1 if (reference.DigestMethod == null) { reference.DigestMethod = XmlDsigSHA1Url; } reference.UpdateHashValue(_containingDocument, nodeList); }
internal static void AddNamespaces(XmlElement elem, CanonicalXmlNodeList namespaces) { if (namespaces != null) { foreach (XmlNode node in namespaces) { string name = (node.Prefix.Length > 0) ? (node.Prefix + ":" + node.LocalName) : node.LocalName; if (!elem.HasAttribute(name) && (!name.Equals("xmlns") || (elem.Prefix.Length != 0))) { XmlAttribute newAttr = elem.OwnerDocument.CreateAttribute(name); newAttr.Value = node.Value; elem.SetAttributeNode(newAttr); } } } }
// // private methods // private byte[] GetC14NDigest(HashAlgorithm hash) { bool isKeyedHashAlgorithm = hash is KeyedHashAlgorithm; string baseUri = _containingDocument?.BaseURI; XmlDocument doc = Utils.PreProcessElementInput(m_signature.GetXml()); // Add non default namespaces in scope CanonicalXmlNodeList namespaces = (_context == null ? null : Utils.GetPropagatedAttributes(_context)); Utils.AddNamespaces(doc.DocumentElement, namespaces); Transform c14nMethodTransform = m_signature.CanonicalizationMethodObject; c14nMethodTransform.LoadInput(doc); return(c14nMethodTransform.GetDigestedOutput(hash)); }
internal static void AddNamespaces(XmlElement elem, CanonicalXmlNodeList namespaces) { if (namespaces != null) { foreach (XmlNode node in namespaces) { string name = (node.Prefix.Length > 0) ? (node.Prefix + ":" + node.LocalName) : node.LocalName; if (!elem.HasAttribute(name) && (!name.Equals("xmlns") || (elem.Prefix.Length != 0))) { XmlAttribute newAttr = elem.OwnerDocument.CreateAttribute(name); newAttr.Value = node.Value; elem.SetAttributeNode(newAttr); } } } }
private void BuildDigestedReferences() { // Default the DigestMethod and Canonicalization ArrayList references = SignedInfo.References; // Reset the cache m_refProcessed = new bool[references.Count]; m_refLevelCache = new int[references.Count]; ReferenceLevelSortOrder sortOrder = new ReferenceLevelSortOrder(); sortOrder.References = references; sortOrder.SignedXml = this; // Don't alter the order of the references array list ArrayList sortedReferences = new ArrayList(); foreach (Reference reference in references) { sortedReferences.Add(reference); } sortedReferences.Sort(sortOrder); CanonicalXmlNodeList nodeList = new CanonicalXmlNodeList(); foreach (DataObject obj in m_signature.ObjectList) { nodeList.Add(obj.GetXml()); } foreach (Reference reference in sortedReferences) { // If no DigestMethod has yet been set, default it to sha1 if (reference.DigestMethod == null) { reference.DigestMethod = XmlDsigSHA1Url; } // propagate namespaces reference.Namespaces = m_namespaces; reference.SignedXml = this; reference.UpdateHashValue(m_containingDocument, nodeList); // If this reference has an Id attribute, add it if (reference.Id != null) { nodeList.Add(reference.GetXml()); } } }
private void BuildDigestedReferences() { // Default the DigestMethod and Canonicalization ArrayList references = SignedInfo.References; // Reset the cache _refProcessed = new bool [references.Count]; _refLevelCache = new int [references.Count]; ReferenceLevelSortOrder sortOrder = new ReferenceLevelSortOrder(); sortOrder.References = references; // Don't alter the order of the references array list ArrayList sortedReferences = new ArrayList(); foreach (Reference reference in references) { sortedReferences.Add(reference); } sortedReferences.Sort(sortOrder); CanonicalXmlNodeList nodeList = new CanonicalXmlNodeList(); foreach (DataObject obj in m_signature.ObjectList) { nodeList.Add(obj.GetXml()); } foreach (Reference reference in sortedReferences) { if (reference.DigestMethod == null) { reference.DigestMethod = XmlDsigDigestDefault; } SignedXmlDebugLog.LogSigningReference(this, reference); reference.UpdateHashValue(_containingDocument, nodeList); // If this reference has an Id attribute, add it if (reference.Id != null) { nodeList.Add(reference.GetXml()); } } }
internal static void AddNamespaces(XmlElement elem, CanonicalXmlNodeList namespaces) { if (namespaces != null) { foreach (XmlNode attrib in namespaces) { string name = ((attrib.Prefix.Length > 0) ? attrib.Prefix + ":" + attrib.LocalName : attrib.LocalName); // Skip the attribute if one with the same qualified name already exists if (elem.HasAttribute(name) || (name.Equals("xmlns") && elem.Prefix.Length == 0)) { continue; } XmlAttribute nsattrib = (XmlAttribute)elem.OwnerDocument.CreateAttribute(name); nsattrib.Value = attrib.Value; elem.SetAttributeNode(nsattrib); } } }
private byte[] GetC14NDigest(HashAlgorithm hash) { if (!this.bCacheValid || !this.SignedInfo.CacheValid) { string securityUrl = (this.m_containingDocument == null) ? null : this.m_containingDocument.BaseURI; XmlResolver xmlResolver = this.m_bResolverSet ? this.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); XmlDocument document = System.Security.Cryptography.Xml.Utils.PreProcessElementInput(this.SignedInfo.GetXml(), xmlResolver, securityUrl); CanonicalXmlNodeList namespaces = (this.m_context == null) ? null : System.Security.Cryptography.Xml.Utils.GetPropagatedAttributes(this.m_context); SignedXmlDebugLog.LogNamespacePropagation(this, namespaces); System.Security.Cryptography.Xml.Utils.AddNamespaces(document.DocumentElement, namespaces); Transform canonicalizationMethodObject = this.SignedInfo.CanonicalizationMethodObject; canonicalizationMethodObject.Resolver = xmlResolver; canonicalizationMethodObject.BaseURI = securityUrl; SignedXmlDebugLog.LogBeginCanonicalization(this, canonicalizationMethodObject); canonicalizationMethodObject.LoadInput(document); SignedXmlDebugLog.LogCanonicalizedOutput(this, canonicalizationMethodObject); this._digestedSignedInfo = canonicalizationMethodObject.GetDigestedOutput(hash); this.bCacheValid = true; } return(this._digestedSignedInfo); }
private static void MarkInclusionStateForNodes(XmlNodeList nodeList, XmlDocument inputRoot, XmlDocument root) { CanonicalXmlNodeList elementList = new CanonicalXmlNodeList(); CanonicalXmlNodeList elementListCanonical = new CanonicalXmlNodeList(); elementList.Add(inputRoot); elementListCanonical.Add(root); int index = 0; do { XmlNode currentNode = (XmlNode)elementList[index]; XmlNode currentNodeCanonical = (XmlNode)elementListCanonical[index]; XmlNodeList childNodes = currentNode.ChildNodes; XmlNodeList childNodesCanonical = currentNodeCanonical.ChildNodes; for (int i = 0; i < childNodes.Count; i++) { elementList.Add(childNodes[i]); elementListCanonical.Add(childNodesCanonical[i]); if (Utils.NodeInList(childNodes[i], nodeList)) { MarkNodeAsIncluded(childNodesCanonical[i]); } XmlAttributeCollection attribNodes = childNodes[i].Attributes; if (attribNodes != null) { for (int j = 0; j < attribNodes.Count; j++) { if (Utils.NodeInList(attribNodes[j], nodeList)) { MarkNodeAsIncluded(childNodesCanonical[i].Attributes.Item(j)); } } } } index++; } while (index < elementList.Count); }
private static void MarkInclusionStateForNodes(XmlNodeList nodeList, XmlDocument inputRoot, XmlDocument root) { CanonicalXmlNodeList list = new CanonicalXmlNodeList(); CanonicalXmlNodeList list2 = new CanonicalXmlNodeList(); list.Add(inputRoot); list2.Add(root); int num = 0; do { XmlNode node = list[num]; XmlNode node2 = list2[num]; XmlNodeList childNodes = node.ChildNodes; XmlNodeList list4 = node2.ChildNodes; for (int i = 0; i < childNodes.Count; i++) { list.Add(childNodes[i]); list2.Add(list4[i]); if (System.Security.Cryptography.Xml.Utils.NodeInList(childNodes[i], nodeList)) { MarkNodeAsIncluded(list4[i]); } XmlAttributeCollection attributes = childNodes[i].Attributes; if (attributes != null) { for (int j = 0; j < attributes.Count; j++) { if (System.Security.Cryptography.Xml.Utils.NodeInList(attributes[j], nodeList)) { MarkNodeAsIncluded(list4[i].Attributes.Item(j)); } } } } num++; }while (num < list.Count); }
private static void MarkInclusionStateForNodes(XmlNodeList nodeList, XmlDocument inputRoot, XmlDocument root) { CanonicalXmlNodeList list = new CanonicalXmlNodeList(); CanonicalXmlNodeList list2 = new CanonicalXmlNodeList(); list.Add(inputRoot); list2.Add(root); int num = 0; do { XmlNode node = list[num]; XmlNode node2 = list2[num]; XmlNodeList childNodes = node.ChildNodes; XmlNodeList list4 = node2.ChildNodes; for (int i = 0; i < childNodes.Count; i++) { list.Add(childNodes[i]); list2.Add(list4[i]); if (System.Security.Cryptography.Xml.Utils.NodeInList(childNodes[i], nodeList)) { MarkNodeAsIncluded(list4[i]); } XmlAttributeCollection attributes = childNodes[i].Attributes; if (attributes != null) { for (int j = 0; j < attributes.Count; j++) { if (System.Security.Cryptography.Xml.Utils.NodeInList(attributes[j], nodeList)) { MarkNodeAsIncluded(list4[i].Attributes.Item(j)); } } } } num++; } while (num < list.Count); }
private void BuildDigestedReferences() { ArrayList references = this.SignedInfo.References; this.m_refProcessed = new bool[references.Count]; this.m_refLevelCache = new int[references.Count]; ReferenceLevelSortOrder comparer = new ReferenceLevelSortOrder { References = references }; ArrayList list2 = new ArrayList(); foreach (Reference reference in references) { list2.Add(reference); } list2.Sort(comparer); CanonicalXmlNodeList refList = new CanonicalXmlNodeList(); foreach (DataObject obj2 in this.m_signature.ObjectList) { refList.Add(obj2.GetXml()); } foreach (Reference reference2 in list2) { if (reference2.DigestMethod == null) { reference2.DigestMethod = "http://www.w3.org/2000/09/xmldsig#sha1"; } SignedXmlDebugLog.LogSigningReference(this, reference2); reference2.UpdateHashValue(this.m_containingDocument, refList); if (reference2.Id != null) { refList.Add(reference2.GetXml()); } } }
// // public constructors // public Signature() { m_embeddedObjects = new ArrayList(); m_referencedItems = new CanonicalXmlNodeList(); }
private void BuildDigestedReferences() { // Default the DigestMethod and Canonicalization ArrayList references = SignedInfo.References; // Reset the cache m_refProcessed = new bool[references.Count]; m_refLevelCache = new int[references.Count]; ReferenceLevelSortOrder sortOrder = new ReferenceLevelSortOrder(); sortOrder.References = references; // Don't alter the order of the references array list ArrayList sortedReferences = new ArrayList(); foreach (Reference reference in references) { sortedReferences.Add(reference); } sortedReferences.Sort(sortOrder); CanonicalXmlNodeList nodeList = new CanonicalXmlNodeList(); foreach (DataObject obj in m_signature.ObjectList) { nodeList.Add(obj.GetXml()); } foreach (Reference reference in sortedReferences) { // If no DigestMethod has yet been set, default it to sha1 if (reference.DigestMethod == null) reference.DigestMethod = XmlDsigSHA1Url; SignedXmlDebugLog.LogSigningReference(this, reference); reference.UpdateHashValue(m_containingDocument, nodeList); // If this reference has an Id attribute, add it if (reference.Id != null) nodeList.Add(reference.GetXml()); } }
// This method gets the attributes that should be propagated internal static CanonicalXmlNodeList GetPropagatedAttributes (XmlElement elem) { if (elem == null) return null; CanonicalXmlNodeList namespaces = new CanonicalXmlNodeList(); XmlNode ancestorNode = elem; if (ancestorNode == null) return null; bool bDefNamespaceToAdd = true; while (ancestorNode != null) { XmlElement ancestorElement = ancestorNode as XmlElement; if (ancestorElement == null) { ancestorNode = ancestorNode.ParentNode; continue; } if (!Utils.IsCommittedNamespace(ancestorElement, ancestorElement.Prefix, ancestorElement.NamespaceURI)) { // Add the namespace attribute to the collection if needed if (!Utils.IsRedundantNamespace(ancestorElement, ancestorElement.Prefix, ancestorElement.NamespaceURI)) { string name = ((ancestorElement.Prefix.Length > 0) ? "xmlns:" + ancestorElement.Prefix : "xmlns"); XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute(name); nsattrib.Value = ancestorElement.NamespaceURI; namespaces.Add(nsattrib); } } if (ancestorElement.HasAttributes) { XmlAttributeCollection attribs = ancestorElement.Attributes; foreach (XmlAttribute attrib in attribs) { // Add a default namespace if necessary if (bDefNamespaceToAdd && attrib.LocalName == "xmlns") { XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute("xmlns"); nsattrib.Value = attrib.Value; namespaces.Add(nsattrib); bDefNamespaceToAdd = false; continue; } // retain the declarations of type 'xml:*' as well if (attrib.Prefix == "xmlns" || attrib.Prefix == "xml") { namespaces.Add(attrib); continue; } if (attrib.NamespaceURI.Length > 0) { if (!Utils.IsCommittedNamespace(ancestorElement, attrib.Prefix, attrib.NamespaceURI)) { // Add the namespace attribute to the collection if needed if (!Utils.IsRedundantNamespace(ancestorElement, attrib.Prefix, attrib.NamespaceURI)) { string name = ((attrib.Prefix.Length > 0) ? "xmlns:" + attrib.Prefix : "xmlns"); XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute(name); nsattrib.Value = attrib.NamespaceURI; namespaces.Add(nsattrib); } } } } } ancestorNode = ancestorNode.ParentNode; } return namespaces; }
internal static void AddNamespaces (XmlElement elem, CanonicalXmlNodeList namespaces) { if (namespaces != null) { foreach (XmlNode attrib in namespaces) { string name = ((attrib.Prefix.Length > 0) ? attrib.Prefix + ":" + attrib.LocalName : attrib.LocalName); // Skip the attribute if one with the same qualified name already exists if (elem.HasAttribute(name) || (name.Equals("xmlns") && elem.Prefix.Length == 0)) continue; XmlAttribute nsattrib = (XmlAttribute) elem.OwnerDocument.CreateAttribute(name); nsattrib.Value = attrib.Value; elem.SetAttributeNode(nsattrib); } } }
public override Object GetOutput() { if (_containingDocument == null) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_EnvelopedSignatureRequiresContext")); // If we have received an XmlNodeList as input if (_inputNodeList != null) { // If the position has not been set, then we don't want to remove any signature tags if (_signaturePosition == 0) return _inputNodeList; XmlNodeList signatureList = _containingDocument.SelectNodes("//dsig:Signature", _nsm); if (signatureList == null) return _inputNodeList; CanonicalXmlNodeList resultNodeList = new CanonicalXmlNodeList(); foreach (XmlNode node in _inputNodeList) { if (node == null) continue; // keep namespaces if (Utils.IsXmlNamespaceNode(node) || Utils.IsNamespaceNode(node)) { resultNodeList.Add(node); } else { // SelectSingleNode throws an exception for xmldecl PI for example, so we will just ignore those exceptions try { // Find the nearest signature ancestor tag XmlNode result = node.SelectSingleNode("ancestor-or-self::dsig:Signature[1]", _nsm); int position = 0; foreach (XmlNode node1 in signatureList) { position++; if (node1 == result) break; } if (result == null || (result != null && position != _signaturePosition)) { resultNodeList.Add(node); } } catch {} } } return resultNodeList; } // Else we have received either a stream or a document as input else { XmlNodeList signatureList = _containingDocument.SelectNodes("//dsig:Signature", _nsm); if (signatureList == null) return _containingDocument; if (signatureList.Count < _signaturePosition || _signaturePosition <= 0) return _containingDocument; // Remove the signature node with all its children nodes signatureList[_signaturePosition - 1].ParentNode.RemoveChild(signatureList[_signaturePosition - 1]); return _containingDocument; } }
public override object GetOutput() { if (this._containingDocument == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_EnvelopedSignatureRequiresContext")); } if (this._inputNodeList != null) { if (this._signaturePosition == 0) { return(this._inputNodeList); } XmlNodeList list = this._containingDocument.SelectNodes("//dsig:Signature", this._nsm); if (list == null) { return(this._inputNodeList); } CanonicalXmlNodeList list2 = new CanonicalXmlNodeList(); foreach (XmlNode node in this._inputNodeList) { if (node != null) { if (System.Security.Cryptography.Xml.Utils.IsXmlNamespaceNode(node) || System.Security.Cryptography.Xml.Utils.IsNamespaceNode(node)) { list2.Add(node); } else { try { XmlNode node2 = node.SelectSingleNode("ancestor-or-self::dsig:Signature[1]", this._nsm); int num = 0; foreach (XmlNode node3 in list) { num++; if (node3 == node2) { break; } } if ((node2 == null) || ((node2 != null) && (num != this._signaturePosition))) { list2.Add(node); } } catch { } } } } return(list2); } XmlNodeList list3 = this._containingDocument.SelectNodes("//dsig:Signature", this._nsm); if (list3 != null) { if ((list3.Count < this._signaturePosition) || (this._signaturePosition <= 0)) { return(this._containingDocument); } list3[this._signaturePosition - 1].ParentNode.RemoveChild(list3[this._signaturePosition - 1]); } return(this._containingDocument); }
internal void UpdateHashValue(XmlDocument document, CanonicalXmlNodeList refList) { DigestValue = CalculateHashValue(document, refList); }
internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList) { this.m_hashAlgorithm = CryptoConfig.CreateFromName(this.m_digestMethod) as HashAlgorithm; if (this.m_hashAlgorithm == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed")); } string securityUrl = (document == null) ? (Environment.CurrentDirectory + @"\") : document.BaseURI; Stream data = null; WebRequest request = null; WebResponse response = null; Stream input = null; XmlResolver resolver = null; byte[] buffer = null; try { switch (this.m_refTargetType) { case System.Security.Cryptography.Xml.ReferenceTargetType.Stream: resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); data = this.TransformChain.TransformToOctetStream((Stream) this.m_refTarget, resolver, securityUrl); goto Label_048A; case System.Security.Cryptography.Xml.ReferenceTargetType.XmlElement: resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); data = this.TransformChain.TransformToOctetStream(System.Security.Cryptography.Xml.Utils.PreProcessElementInput((XmlElement) this.m_refTarget, resolver, securityUrl), resolver, securityUrl); goto Label_048A; case System.Security.Cryptography.Xml.ReferenceTargetType.UriReference: if (this.m_uri != null) { break; } resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); data = this.TransformChain.TransformToOctetStream((Stream) null, resolver, securityUrl); goto Label_048A; default: goto Label_0474; } if (this.m_uri.Length == 0) { if (document == null) { throw new CryptographicException(string.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"), new object[] { this.m_uri })); } resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); XmlDocument document2 = System.Security.Cryptography.Xml.Utils.DiscardComments(System.Security.Cryptography.Xml.Utils.PreProcessDocumentInput(document, resolver, securityUrl)); data = this.TransformChain.TransformToOctetStream(document2, resolver, securityUrl); goto Label_048A; } if (this.m_uri[0] == '#') { bool discardComments = true; string idFromLocalUri = System.Security.Cryptography.Xml.Utils.GetIdFromLocalUri(this.m_uri, out discardComments); if (idFromLocalUri == "xpointer(/)") { if (document == null) { throw new CryptographicException(string.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"), new object[] { this.m_uri })); } resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); data = this.TransformChain.TransformToOctetStream(System.Security.Cryptography.Xml.Utils.PreProcessDocumentInput(document, resolver, securityUrl), resolver, securityUrl); } else { XmlElement idElement = this.SignedXml.GetIdElement(document, idFromLocalUri); if (idElement != null) { this.m_namespaces = System.Security.Cryptography.Xml.Utils.GetPropagatedAttributes(idElement.ParentNode as XmlElement); } if ((idElement == null) && (refList != null)) { foreach (XmlNode node in refList) { XmlElement element = node as XmlElement; if (((element != null) && System.Security.Cryptography.Xml.Utils.HasAttribute(element, "Id", "http://www.w3.org/2000/09/xmldsig#")) && System.Security.Cryptography.Xml.Utils.GetAttribute(element, "Id", "http://www.w3.org/2000/09/xmldsig#").Equals(idFromLocalUri)) { idElement = element; if (this.m_signedXml.m_context != null) { this.m_namespaces = System.Security.Cryptography.Xml.Utils.GetPropagatedAttributes(this.m_signedXml.m_context); } break; } } } if (idElement == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidReference")); } XmlDocument document3 = System.Security.Cryptography.Xml.Utils.PreProcessElementInput(idElement, resolver, securityUrl); System.Security.Cryptography.Xml.Utils.AddNamespaces(document3.DocumentElement, this.m_namespaces); resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); if (discardComments) { XmlDocument document4 = System.Security.Cryptography.Xml.Utils.DiscardComments(document3); data = this.TransformChain.TransformToOctetStream(document4, resolver, securityUrl); } else { data = this.TransformChain.TransformToOctetStream(document3, resolver, securityUrl); } } goto Label_048A; } System.Uri relativeUri = new System.Uri(this.m_uri, UriKind.RelativeOrAbsolute); if (!relativeUri.IsAbsoluteUri) { relativeUri = new System.Uri(new System.Uri(securityUrl), relativeUri); } request = WebRequest.Create(relativeUri); if (request != null) { response = request.GetResponse(); if (response != null) { input = response.GetResponseStream(); if (input != null) { resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); data = this.TransformChain.TransformToOctetStream(input, resolver, this.m_uri); goto Label_048A; } } } Label_0474: throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), this.m_uri); Label_048A: data = SignedXmlDebugLog.LogReferenceData(this, data); buffer = this.m_hashAlgorithm.ComputeHash(data); } finally { if (data != null) { data.Close(); } if (response != null) { response.Close(); } if (input != null) { input.Close(); } } return buffer; }
public DataObject() { this.m_cachedXml = null; this.m_elData = new CanonicalXmlNodeList(); }
internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList) { // refList is a list of elements that might be targets of references // Now's the time to create our hashing algorithm m_hashAlgorithm = CryptoConfig.CreateFromName(m_digestMethod) as HashAlgorithm; if (m_hashAlgorithm == null) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed")); // Let's go get the target. string baseUri = (document == null ? System.Environment.CurrentDirectory + "\\" : document.BaseURI); Stream hashInputStream = null; WebRequest request = null; WebResponse response = null; Stream inputStream = null; XmlResolver resolver = null; byte[] hashval = null; try { switch (m_refTargetType) { case ReferenceTargetType.Stream: // This is the easiest case. We already have a stream, so just pump it through the TransformChain resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = this.TransformChain.TransformToOctetStream((Stream) m_refTarget, resolver, baseUri); break; case ReferenceTargetType.UriReference: // Second-easiest case -- dereference the URI & pump through the TransformChain // handle the special cases where the URI is null (meaning whole doc) // or the URI is just a fragment (meaning a reference to an embedded Object) if (m_uri == null) { // We need to create a DocumentNavigator out of the XmlElement resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); // In the case of a Uri-less reference, we will simply pass null to the transform chain. // The first transform in the chain is expected to know how to retrieve the data to hash. hashInputStream = this.TransformChain.TransformToOctetStream((Stream) null, resolver, baseUri); } else if (m_uri.Length == 0) { // This is the self-referential case. First, check that we have a document context. // The Enveloped Signature does not discard comments as per spec; those will be omitted during the transform chain process if (document == null) throw new CryptographicException(String.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"), m_uri)); // Normalize the containing document resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); XmlDocument docWithNoComments = Utils.DiscardComments(Utils.PreProcessDocumentInput(document, resolver, baseUri)); hashInputStream = this.TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri); } else if (m_uri[0] == '#') { // If we get here, then we are constructing a Reference to an embedded DataObject // referenced by an Id = attribute. Go find the relevant object bool discardComments = true; string idref = Utils.GetIdFromLocalUri(m_uri, out discardComments); if (idref == "xpointer(/)") { // This is a self referencial case if (document == null) throw new CryptographicException(String.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"),m_uri)); // We should not discard comments here!!! resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = this.TransformChain.TransformToOctetStream(Utils.PreProcessDocumentInput(document, resolver, baseUri), resolver, baseUri); break; } XmlElement elem = this.SignedXml.GetIdElement(document, idref); if (elem != null) m_namespaces = Utils.GetPropagatedAttributes(elem.ParentNode as XmlElement); if (elem == null) { // Go throw the referenced items passed in if (refList != null) { foreach (XmlNode node in refList) { XmlElement tempElem = node as XmlElement; if ((tempElem != null) && (Utils.HasAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl)) && (Utils.GetAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl).Equals(idref))) { elem = tempElem; if (this.m_signedXml.m_context != null) m_namespaces = Utils.GetPropagatedAttributes(this.m_signedXml.m_context); break; } } } } if (elem == null) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidReference")); XmlDocument normDocument = Utils.PreProcessElementInput(elem, resolver, baseUri); // Add the propagated attributes Utils.AddNamespaces(normDocument.DocumentElement, m_namespaces); resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); if (discardComments) { // We should discard comments before going into the transform chain XmlDocument docWithNoComments = Utils.DiscardComments(normDocument); hashInputStream = this.TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri); } else { // This is an XPointer reference, do not discard comments!!! hashInputStream = this.TransformChain.TransformToOctetStream(normDocument, resolver, baseUri); } } else { // WebRequest always expects an Absolute Uri, so try to resolve if we were passed a relative Uri. System.Uri uri = new System.Uri(m_uri, UriKind.RelativeOrAbsolute); if (!uri.IsAbsoluteUri) { uri = new Uri(new Uri(baseUri), uri); } request = WebRequest.Create(uri); if (request == null) goto default; response = request.GetResponse(); if (response == null) goto default; inputStream = response.GetResponseStream(); if (inputStream == null) goto default; resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = this.TransformChain.TransformToOctetStream(inputStream, resolver, m_uri); } break; case ReferenceTargetType.XmlElement: // We need to create a DocumentNavigator out of the XmlElement resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = this.TransformChain.TransformToOctetStream(Utils.PreProcessElementInput((XmlElement) m_refTarget, resolver, baseUri), resolver, baseUri); break; default: throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), m_uri); } // Compute the new hash value hashInputStream = SignedXmlDebugLog.LogReferenceData(this, hashInputStream); hashval = m_hashAlgorithm.ComputeHash(hashInputStream); } finally { if (hashInputStream != null) hashInputStream.Close(); if (response != null) response.Close(); if (inputStream != null) inputStream.Close(); } return hashval; }
internal void UpdateHashValue(XmlDocument document, CanonicalXmlNodeList refList) { this.DigestValue = this.CalculateHashValue(document, refList); }
internal static CanonicalXmlNodeList GetPropagatedAttributes(XmlElement elem) { if (elem == null) { return null; } CanonicalXmlNodeList list = new CanonicalXmlNodeList(); XmlNode parentNode = elem; if (parentNode == null) { return null; } bool flag = true; while (parentNode != null) { XmlElement element = parentNode as XmlElement; if (element == null) { parentNode = parentNode.ParentNode; } else { if (!IsCommittedNamespace(element, element.Prefix, element.NamespaceURI) && !IsRedundantNamespace(element, element.Prefix, element.NamespaceURI)) { string name = (element.Prefix.Length > 0) ? ("xmlns:" + element.Prefix) : "xmlns"; XmlAttribute attribute = elem.OwnerDocument.CreateAttribute(name); attribute.Value = element.NamespaceURI; list.Add(attribute); } if (element.HasAttributes) { foreach (XmlAttribute attribute2 in element.Attributes) { if (flag && (attribute2.LocalName == "xmlns")) { XmlAttribute attribute3 = elem.OwnerDocument.CreateAttribute("xmlns"); attribute3.Value = attribute2.Value; list.Add(attribute3); flag = false; } else if ((attribute2.Prefix == "xmlns") || (attribute2.Prefix == "xml")) { list.Add(attribute2); } else if (((attribute2.NamespaceURI.Length > 0) && !IsCommittedNamespace(element, attribute2.Prefix, attribute2.NamespaceURI)) && !IsRedundantNamespace(element, attribute2.Prefix, attribute2.NamespaceURI)) { string str2 = (attribute2.Prefix.Length > 0) ? ("xmlns:" + attribute2.Prefix) : "xmlns"; XmlAttribute attribute4 = elem.OwnerDocument.CreateAttribute(str2); attribute4.Value = attribute2.NamespaceURI; list.Add(attribute4); } } } parentNode = parentNode.ParentNode; } } return list; }
// // public constructors // public Signature() { m_embeddedObjects = new ArrayList(); m_referencedItems = new CanonicalXmlNodeList(); }
private void BuildDigestedReferences() { ArrayList references = this.SignedInfo.References; this.m_refProcessed = new bool[references.Count]; this.m_refLevelCache = new int[references.Count]; ReferenceLevelSortOrder comparer = new ReferenceLevelSortOrder { References = references }; ArrayList list2 = new ArrayList(); foreach (Reference reference in references) { list2.Add(reference); } list2.Sort(comparer); CanonicalXmlNodeList refList = new CanonicalXmlNodeList(); foreach (DataObject obj2 in this.m_signature.ObjectList) { refList.Add(obj2.GetXml()); } foreach (Reference reference2 in list2) { if (reference2.DigestMethod == null) { reference2.DigestMethod = "http://www.w3.org/2000/09/xmldsig#sha1"; } SignedXmlDebugLog.LogSigningReference(this, reference2); reference2.UpdateHashValue(this.m_containingDocument, refList); if (reference2.Id != null) { refList.Add(reference2.GetXml()); } } }
public override object GetOutput() { if (_containingDocument == null) { throw new CryptographicException(SR.Cryptography_Xml_EnvelopedSignatureRequiresContext); } // If we have received an XmlNodeList as input if (_inputNodeList != null) { // If the position has not been set, then we don't want to remove any signature tags if (_signaturePosition == 0) { return(_inputNodeList); } XmlNodeList signatureList = _containingDocument.SelectNodes("//dsig:Signature", _nsm); if (signatureList == null) { return(_inputNodeList); } CanonicalXmlNodeList resultNodeList = new CanonicalXmlNodeList(); foreach (XmlNode node in _inputNodeList) { if (node == null) { continue; } // keep namespaces if (Utils.IsXmlNamespaceNode(node) || Utils.IsNamespaceNode(node)) { resultNodeList.Add(node); } else { // SelectSingleNode throws an exception for xmldecl PI for example, so we will just ignore those exceptions try { // Find the nearest signature ancestor tag XmlNode result = node.SelectSingleNode("ancestor-or-self::dsig:Signature[1]", _nsm); int position = 0; foreach (XmlNode node1 in signatureList) { position++; if (node1 == result) { break; } } if (result == null || position != _signaturePosition) { resultNodeList.Add(node); } } catch { } } } return(resultNodeList); } // Else we have received either a stream or a document as input else { XmlNodeList signatureList = _containingDocument.SelectNodes("//dsig:Signature", _nsm); if (signatureList == null) { return(_containingDocument); } if (signatureList.Count < _signaturePosition || _signaturePosition <= 0) { return(_containingDocument); } // Remove the signature node with all its children nodes signatureList[_signaturePosition - 1].ParentNode.RemoveChild(signatureList[_signaturePosition - 1]); return(_containingDocument); } }
// What we want to do is pump the input throug the TransformChain and then // hash the output of the chain document is the document context for resolving relative references internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList) { // refList is a list of elements that might be targets of references // Now's the time to create our hashing algorithm _hashAlgorithm = CryptoHelpers.CreateFromName <HashAlgorithm>(_digestMethod); if (_hashAlgorithm == null) { throw new CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed); } // Let's go get the target. string baseUri = (document == null ? System.Environment.CurrentDirectory + "\\" : document.BaseURI); Stream hashInputStream = null; WebResponse response = null; Stream inputStream = null; XmlResolver resolver = null; byte[] hashval = null; try { switch (_refTargetType) { case ReferenceTargetType.Stream: // This is the easiest case. We already have a stream, so just pump it through the TransformChain resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = TransformChain.TransformToOctetStream((Stream)_refTarget, resolver, baseUri); break; case ReferenceTargetType.UriReference: // Second-easiest case -- dereference the URI & pump through the TransformChain // handle the special cases where the URI is null (meaning whole doc) // or the URI is just a fragment (meaning a reference to an embedded Object) if (_uri == null) { // We need to create a DocumentNavigator out of the XmlElement resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); // In the case of a Uri-less reference, we will simply pass null to the transform chain. // The first transform in the chain is expected to know how to retrieve the data to hash. hashInputStream = TransformChain.TransformToOctetStream((Stream)null, resolver, baseUri); } else if (_uri.Length == 0) { // This is the self-referential case. First, check that we have a document context. // The Enveloped Signature does not discard comments as per spec; those will be omitted during the transform chain process if (document == null) { throw new CryptographicException(SR.Format(SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri)); } // Normalize the containing document resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); XmlDocument docWithNoComments = Utils.DiscardComments(Utils.PreProcessDocumentInput(document, resolver, baseUri)); hashInputStream = TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri); } else if (_uri[0] == '#') { // If we get here, then we are constructing a Reference to an embedded DataObject // referenced by an Id = attribute. Go find the relevant object bool discardComments = true; string idref = Utils.GetIdFromLocalUri(_uri, out discardComments); if (idref == "xpointer(/)") { // This is a self referencial case if (document == null) { throw new CryptographicException(SR.Format(SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri)); } // We should not discard comments here!!! resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = TransformChain.TransformToOctetStream(Utils.PreProcessDocumentInput(document, resolver, baseUri), resolver, baseUri); break; } XmlElement elem = SignedXml.GetIdElement(document, idref); if (elem != null) { _namespaces = Utils.GetPropagatedAttributes(elem.ParentNode as XmlElement); } if (elem == null) { // Go throw the referenced items passed in if (refList != null) { foreach (XmlNode node in refList) { XmlElement tempElem = node as XmlElement; if ((tempElem != null) && (Utils.HasAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl)) && (Utils.GetAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl).Equals(idref))) { elem = tempElem; if (_signedXml._context != null) { _namespaces = Utils.GetPropagatedAttributes(_signedXml._context); } break; } } } } if (elem == null) { throw new CryptographicException(SR.Cryptography_Xml_InvalidReference); } XmlDocument normDocument = Utils.PreProcessElementInput(elem, resolver, baseUri); // Add the propagated attributes Utils.AddNamespaces(normDocument.DocumentElement, _namespaces); resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); if (discardComments) { // We should discard comments before going into the transform chain XmlDocument docWithNoComments = Utils.DiscardComments(normDocument); hashInputStream = TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri); } else { // This is an XPointer reference, do not discard comments!!! hashInputStream = TransformChain.TransformToOctetStream(normDocument, resolver, baseUri); } } else { throw new CryptographicException(SR.Cryptography_Xml_UriNotResolved, _uri); } break; case ReferenceTargetType.XmlElement: // We need to create a DocumentNavigator out of the XmlElement resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = TransformChain.TransformToOctetStream(Utils.PreProcessElementInput((XmlElement)_refTarget, resolver, baseUri), resolver, baseUri); break; default: throw new CryptographicException(SR.Cryptography_Xml_UriNotResolved, _uri); } // Compute the new hash value hashInputStream = SignedXmlDebugLog.LogReferenceData(this, hashInputStream); hashval = _hashAlgorithm.ComputeHash(hashInputStream); } finally { if (hashInputStream != null) { hashInputStream.Close(); } if (response != null) { response.Close(); } if (inputStream != null) { inputStream.Close(); } } return(hashval); }
internal static XmlNodeList AllDescendantNodes (XmlNode node, bool includeComments) { CanonicalXmlNodeList nodeList = new CanonicalXmlNodeList(); CanonicalXmlNodeList elementList = new CanonicalXmlNodeList(); CanonicalXmlNodeList attribList = new CanonicalXmlNodeList(); CanonicalXmlNodeList namespaceList = new CanonicalXmlNodeList(); int index = 0; elementList.Add(node); do { XmlNode rootNode = (XmlNode) elementList[index]; // Add the children nodes XmlNodeList childNodes = rootNode.ChildNodes; if (childNodes != null) { foreach (XmlNode node1 in childNodes) { if (includeComments || (!(node1 is XmlComment))) { elementList.Add(node1); } } } // Add the attribute nodes XmlAttributeCollection attribNodes = rootNode.Attributes; if (attribNodes != null) { foreach (XmlNode attribNode in rootNode.Attributes) { if (attribNode.LocalName == "xmlns" || attribNode.Prefix == "xmlns") namespaceList.Add(attribNode); else attribList.Add(attribNode); } } index++; } while (index < elementList.Count); foreach (XmlNode elementNode in elementList) { nodeList.Add(elementNode); } foreach (XmlNode attribNode in attribList) { nodeList.Add(attribNode); } foreach (XmlNode namespaceNode in namespaceList) { nodeList.Add(namespaceNode); } return nodeList; }
internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList) { this.m_hashAlgorithm = CryptoConfig.CreateFromName(this.m_digestMethod) as HashAlgorithm; if (this.m_hashAlgorithm == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed")); } string securityUrl = (document == null) ? (Environment.CurrentDirectory + @"\") : document.BaseURI; Stream data = null; WebRequest request = null; WebResponse response = null; Stream input = null; XmlResolver resolver = null; byte[] buffer = null; try { switch (this.m_refTargetType) { case System.Security.Cryptography.Xml.ReferenceTargetType.Stream: resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); data = this.TransformChain.TransformToOctetStream((Stream)this.m_refTarget, resolver, securityUrl); goto Label_048A; case System.Security.Cryptography.Xml.ReferenceTargetType.XmlElement: resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); data = this.TransformChain.TransformToOctetStream(System.Security.Cryptography.Xml.Utils.PreProcessElementInput((XmlElement)this.m_refTarget, resolver, securityUrl), resolver, securityUrl); goto Label_048A; case System.Security.Cryptography.Xml.ReferenceTargetType.UriReference: if (this.m_uri != null) { break; } resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); data = this.TransformChain.TransformToOctetStream((Stream)null, resolver, securityUrl); goto Label_048A; default: goto Label_0474; } if (this.m_uri.Length == 0) { if (document == null) { throw new CryptographicException(string.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"), new object[] { this.m_uri })); } resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); XmlDocument document2 = System.Security.Cryptography.Xml.Utils.DiscardComments(System.Security.Cryptography.Xml.Utils.PreProcessDocumentInput(document, resolver, securityUrl)); data = this.TransformChain.TransformToOctetStream(document2, resolver, securityUrl); goto Label_048A; } if (this.m_uri[0] == '#') { bool discardComments = true; string idFromLocalUri = System.Security.Cryptography.Xml.Utils.GetIdFromLocalUri(this.m_uri, out discardComments); if (idFromLocalUri == "xpointer(/)") { if (document == null) { throw new CryptographicException(string.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"), new object[] { this.m_uri })); } resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); data = this.TransformChain.TransformToOctetStream(System.Security.Cryptography.Xml.Utils.PreProcessDocumentInput(document, resolver, securityUrl), resolver, securityUrl); } else { XmlElement idElement = this.SignedXml.GetIdElement(document, idFromLocalUri); if (idElement != null) { this.m_namespaces = System.Security.Cryptography.Xml.Utils.GetPropagatedAttributes(idElement.ParentNode as XmlElement); } if ((idElement == null) && (refList != null)) { foreach (XmlNode node in refList) { XmlElement element = node as XmlElement; if (((element != null) && System.Security.Cryptography.Xml.Utils.HasAttribute(element, "Id", "http://www.w3.org/2000/09/xmldsig#")) && System.Security.Cryptography.Xml.Utils.GetAttribute(element, "Id", "http://www.w3.org/2000/09/xmldsig#").Equals(idFromLocalUri)) { idElement = element; if (this.m_signedXml.m_context != null) { this.m_namespaces = System.Security.Cryptography.Xml.Utils.GetPropagatedAttributes(this.m_signedXml.m_context); } break; } } } if (idElement == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidReference")); } XmlDocument document3 = System.Security.Cryptography.Xml.Utils.PreProcessElementInput(idElement, resolver, securityUrl); System.Security.Cryptography.Xml.Utils.AddNamespaces(document3.DocumentElement, this.m_namespaces); resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); if (discardComments) { XmlDocument document4 = System.Security.Cryptography.Xml.Utils.DiscardComments(document3); data = this.TransformChain.TransformToOctetStream(document4, resolver, securityUrl); } else { data = this.TransformChain.TransformToOctetStream(document3, resolver, securityUrl); } } goto Label_048A; } System.Uri relativeUri = new System.Uri(this.m_uri, UriKind.RelativeOrAbsolute); if (!relativeUri.IsAbsoluteUri) { relativeUri = new System.Uri(new System.Uri(securityUrl), relativeUri); } request = WebRequest.Create(relativeUri); if (request != null) { response = request.GetResponse(); if (response != null) { input = response.GetResponseStream(); if (input != null) { resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl); data = this.TransformChain.TransformToOctetStream(input, resolver, this.m_uri); goto Label_048A; } } } Label_0474: throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), this.m_uri); Label_048A: data = SignedXmlDebugLog.LogReferenceData(this, data); buffer = this.m_hashAlgorithm.ComputeHash(data); } finally { if (data != null) { data.Close(); } if (response != null) { response.Close(); } if (input != null) { input.Close(); } } return(buffer); }
public override Object GetOutput() { CanonicalXmlNodeList resultNodeList = new CanonicalXmlNodeList(); if (!String.IsNullOrEmpty(_xpathexpr)) { XPathNavigator navigator = _document.CreateNavigator(); XPathNodeIterator it = navigator.Select("//. | //@*"); XPathExpression xpathExpr = navigator.Compile("boolean(" + _xpathexpr + ")"); xpathExpr.SetContext(_nsm); while (it.MoveNext()) { XmlNode node = ((IHasXmlNode) it.Current).GetNode(); bool include = (bool) it.Current.Evaluate(xpathExpr); if (include == true) resultNodeList.Add(node); } // keep namespaces it = navigator.Select("//namespace::*"); while (it.MoveNext()) { XmlNode node = ((IHasXmlNode) it.Current).GetNode(); resultNodeList.Add(node); } } return resultNodeList; }
// This method gets the attributes that should be propagated internal static CanonicalXmlNodeList GetPropagatedAttributes(XmlElement elem) { if (elem == null) { return(null); } CanonicalXmlNodeList namespaces = new CanonicalXmlNodeList(); XmlNode ancestorNode = elem; bool bDefNamespaceToAdd = true; while (ancestorNode != null) { XmlElement ancestorElement = ancestorNode as XmlElement; if (ancestorElement == null) { ancestorNode = ancestorNode.ParentNode; continue; } if (!Utils.IsCommittedNamespace(ancestorElement, ancestorElement.Prefix, ancestorElement.NamespaceURI)) { // Add the namespace attribute to the collection if needed if (!Utils.IsRedundantNamespace(ancestorElement, ancestorElement.Prefix, ancestorElement.NamespaceURI)) { string name = ((ancestorElement.Prefix.Length > 0) ? "xmlns:" + ancestorElement.Prefix : "xmlns"); XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute(name); nsattrib.Value = ancestorElement.NamespaceURI; namespaces.Add(nsattrib); } } if (ancestorElement.HasAttributes) { XmlAttributeCollection attribs = ancestorElement.Attributes; foreach (XmlAttribute attrib in attribs) { // Add a default namespace if necessary if (bDefNamespaceToAdd && attrib.LocalName == "xmlns") { XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute("xmlns"); nsattrib.Value = attrib.Value; namespaces.Add(nsattrib); bDefNamespaceToAdd = false; continue; } // retain the declarations of type 'xml:*' as well if (attrib.Prefix == "xmlns" || attrib.Prefix == "xml") { namespaces.Add(attrib); continue; } if (attrib.NamespaceURI.Length > 0) { if (!Utils.IsCommittedNamespace(ancestorElement, attrib.Prefix, attrib.NamespaceURI)) { // Add the namespace attribute to the collection if needed if (!Utils.IsRedundantNamespace(ancestorElement, attrib.Prefix, attrib.NamespaceURI)) { string name = ((attrib.Prefix.Length > 0) ? "xmlns:" + attrib.Prefix : "xmlns"); XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute(name); nsattrib.Value = attrib.NamespaceURI; namespaces.Add(nsattrib); } } } } } ancestorNode = ancestorNode.ParentNode; } return(namespaces); }
public override object GetOutput() { if (this._containingDocument == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_EnvelopedSignatureRequiresContext")); } if (this._inputNodeList != null) { if (this._signaturePosition == 0) { return this._inputNodeList; } XmlNodeList list = this._containingDocument.SelectNodes("//dsig:Signature", this._nsm); if (list == null) { return this._inputNodeList; } CanonicalXmlNodeList list2 = new CanonicalXmlNodeList(); foreach (XmlNode node in this._inputNodeList) { if (node != null) { if (System.Security.Cryptography.Xml.Utils.IsXmlNamespaceNode(node) || System.Security.Cryptography.Xml.Utils.IsNamespaceNode(node)) { list2.Add(node); } else { try { XmlNode node2 = node.SelectSingleNode("ancestor-or-self::dsig:Signature[1]", this._nsm); int num = 0; foreach (XmlNode node3 in list) { num++; if (node3 == node2) { break; } } if ((node2 == null) || ((node2 != null) && (num != this._signaturePosition))) { list2.Add(node); } } catch { } } } } return list2; } XmlNodeList list3 = this._containingDocument.SelectNodes("//dsig:Signature", this._nsm); if (list3 != null) { if ((list3.Count < this._signaturePosition) || (this._signaturePosition <= 0)) { return this._containingDocument; } list3[this._signaturePosition - 1].ParentNode.RemoveChild(list3[this._signaturePosition - 1]); } return this._containingDocument; }