public void EmptyChain () 
		{
			TransformChain chain = new TransformChain ();
			AssertEquals ("empty count", 0, chain.Count);
			AssertNotNull ("IEnumerator", chain.GetEnumerator ());
			AssertEquals ("ToString()", "System.Security.Cryptography.Xml.TransformChain", chain.ToString ());
		}
Esempio n. 2
0
        private void DownloadCipherValue(CipherData cipherData, out Stream inputStream, out Stream decInputStream, out WebResponse response)
        {
            // maybe a network stream, make sure we allow just what is needed!!
            PermissionSet ps = SecurityManager.GetStandardSandbox(m_evidence);

            ps.PermitOnly();
            WebRequest request = WebRequest.Create(cipherData.CipherReference.Uri);

            if (request == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), cipherData.CipherReference.Uri);
            }
            response = request.GetResponse();
            if (response == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), cipherData.CipherReference.Uri);
            }
            inputStream = response.GetResponseStream();
            if (inputStream == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), cipherData.CipherReference.Uri);
            }
            TransformChain tc = cipherData.CipherReference.TransformChain;

            decInputStream = tc.TransformToOctetStream(inputStream, m_xmlResolver, cipherData.CipherReference.Uri);
        }
		public void FullChain () 
		{
			TransformChain chain = new TransformChain ();

			XmlDsigBase64Transform base64 = new XmlDsigBase64Transform ();
			chain.Add (base64);
			AssertEquals ("XmlDsigBase64Transform", base64, chain[0]);
			AssertEquals ("count 1", 1, chain.Count);

			XmlDsigC14NTransform c14n = new XmlDsigC14NTransform ();
			chain.Add (c14n);
			AssertEquals ("XmlDsigC14NTransform", c14n, chain[1]);
			AssertEquals ("count 2", 2, chain.Count);

			XmlDsigC14NWithCommentsTransform c14nc = new XmlDsigC14NWithCommentsTransform ();
			chain.Add (c14nc);
			AssertEquals ("XmlDsigC14NWithCommentsTransform", c14nc, chain[2]);
			AssertEquals ("count 3", 3, chain.Count);

			XmlDsigEnvelopedSignatureTransform esign = new XmlDsigEnvelopedSignatureTransform ();
			chain.Add (esign);
			AssertEquals ("XmlDsigEnvelopedSignatureTransform", esign, chain[3]);
			AssertEquals ("count 4", 4, chain.Count);

			XmlDsigXPathTransform xpath = new XmlDsigXPathTransform ();
			chain.Add (xpath);
			AssertEquals ("XmlDsigXPathTransform", xpath, chain[4]);
			AssertEquals ("count 5", 5, chain.Count);

			XmlDsigXsltTransform xslt = new XmlDsigXsltTransform ();
			chain.Add (xslt);
			AssertEquals ("XmlDsigXsltTransform", xslt, chain[5]);
			AssertEquals ("count 6", 6, chain.Count);
		}
Esempio n. 4
0
 internal Reference (XmlElement element) {
     m_transformChain = new TransformChain();
     m_refTarget = element;
     m_refTargetType = ReferenceTargetType.XmlElement;
     m_cachedXml = null;
     m_digestMethod = SignedXml.XmlDsigSHA1Url;
 }
Esempio n. 5
0
 public Reference (Stream stream) {
     m_transformChain = new TransformChain();
     m_refTarget = stream;
     m_refTargetType = ReferenceTargetType.Stream;
     m_cachedXml = null;
     m_digestMethod = SignedXml.XmlDsigSHA1Url;
 }
Esempio n. 6
0
		public void FullChain () 
		{
			TransformChain chain = new TransformChain ();

			XmlDsigBase64Transform base64 = new XmlDsigBase64Transform ();
			chain.Add (base64);
			Assert.AreEqual (base64, chain[0], "XmlDsigBase64Transform");
			Assert.AreEqual (1, chain.Count, "count 1");

			XmlDsigC14NTransform c14n = new XmlDsigC14NTransform ();
			chain.Add (c14n);
			Assert.AreEqual (c14n, chain[1], "XmlDsigC14NTransform");
			Assert.AreEqual (2, chain.Count, "count 2");

			XmlDsigC14NWithCommentsTransform c14nc = new XmlDsigC14NWithCommentsTransform ();
			chain.Add (c14nc);
			Assert.AreEqual (c14nc, chain[2], "XmlDsigC14NWithCommentsTransform");
			Assert.AreEqual (3, chain.Count, "count 3");

			XmlDsigEnvelopedSignatureTransform esign = new XmlDsigEnvelopedSignatureTransform ();
			chain.Add (esign);
			Assert.AreEqual (esign, chain[3], "XmlDsigEnvelopedSignatureTransform");
			Assert.AreEqual (4, chain.Count, "count 4");

			XmlDsigXPathTransform xpath = new XmlDsigXPathTransform ();
			chain.Add (xpath);
			Assert.AreEqual (xpath, chain[4], "XmlDsigXPathTransform");
			Assert.AreEqual (5, chain.Count, "count 5");

			XmlDsigXsltTransform xslt = new XmlDsigXsltTransform ();
			chain.Add (xslt);
			Assert.AreEqual (xslt, chain[5], "XmlDsigXsltTransform");
			Assert.AreEqual (6, chain.Count, "count 6");
		}
Esempio n. 7
0
		public void EmptyChain () 
		{
			TransformChain chain = new TransformChain ();
			Assert.AreEqual (0, chain.Count, "empty count");
			Assert.IsNotNull (chain.GetEnumerator (), "IEnumerator");
			Assert.AreEqual ("System.Security.Cryptography.Xml.TransformChain", chain.ToString (), "ToString()");
		}
Esempio n. 8
0
        private static SignatureVerificationResult VerifyStrongNameSignatureTransforms(SignedInfo signedInfo)
        {
            int num = 0;

            foreach (Reference reference in signedInfo.References)
            {
                TransformChain transformChain = reference.TransformChain;
                bool           flag           = false;
                if (string.IsNullOrEmpty(reference.Uri))
                {
                    num++;
                    flag = (((transformChain != null) && (transformChain.Count == 2)) && (string.Compare(transformChain[0].Algorithm, "http://www.w3.org/2000/09/xmldsig#enveloped-signature", StringComparison.Ordinal) == 0)) && (string.Compare(transformChain[1].Algorithm, "http://www.w3.org/2001/10/xml-exc-c14n#", StringComparison.Ordinal) == 0);
                }
                else if (string.Compare(reference.Uri, "#StrongNameKeyInfo", StringComparison.Ordinal) == 0)
                {
                    num++;
                    flag = ((transformChain != null) && (transformChain.Count == 1)) && (string.Compare(transformChain[0].Algorithm, "http://www.w3.org/2001/10/xml-exc-c14n#", StringComparison.Ordinal) == 0);
                }
                else
                {
                    flag = true;
                }
                if (!flag)
                {
                    return(SignatureVerificationResult.BadSignatureFormat);
                }
            }
            if (num == 0)
            {
                return(SignatureVerificationResult.BadSignatureFormat);
            }
            return(SignatureVerificationResult.Valid);
        }
Esempio n. 9
0
        //
        // public methods
        //

        internal XmlElement GetXml(XmlDocument document)
        {
            // Create the Reference
            XmlElement referenceElement = document.CreateElement("Reference", SignedXml.XmlDsigNamespaceUrl);

            if (_uri != null)
            {
                referenceElement.SetAttribute("URI", _uri);
            }

            // Add the transforms to the Reference
            if (TransformChain.Count != 0)
            {
                referenceElement.AppendChild(TransformChain.GetXml(document, SignedXml.XmlDsigNamespaceUrl));
            }

            // Add the DigestMethod
            XmlElement digestMethodElement = document.CreateElement("DigestMethod", SignedXml.XmlDsigNamespaceUrl);

            digestMethodElement.SetAttribute("Algorithm", _digestMethod);
            referenceElement.AppendChild(digestMethodElement);

            XmlElement digestValueElement = document.CreateElement("DigestValue", SignedXml.XmlDsigNamespaceUrl);

            digestValueElement.AppendChild(document.CreateTextNode(Convert.ToBase64String(_digestValue)));
            referenceElement.AppendChild(digestValueElement);

            return(referenceElement);
        }
Esempio n. 10
0
        public override void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            ReferenceType = value.LocalName;
            string uri = Utils.GetAttribute(value, "URI", EncryptedXml.XmlEncNamespaceUrl);

            Uri = uri ?? throw new CryptographicException(SR.Cryptography_Xml_UriRequired);

            // Transforms
            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl);
            XmlNode transformsNode = value.SelectSingleNode("enc:Transforms", nsm);

            if (transformsNode != null)
            {
                TransformChain.LoadXml(transformsNode as XmlElement);
            }

            // cache the Xml
            _cachedXml = value;
        }
Esempio n. 11
0
        //
        // public constructors
        //

        public Reference()
        {
            m_transformChain = new TransformChain();
            m_refTarget      = null;
            m_refTargetType  = ReferenceTargetType.UriReference;
            m_cachedXml      = null;
            m_digestMethod   = SignedXml.XmlDsigDigestDefault;
        }
Esempio n. 12
0
 public Reference (string uri) {
     m_transformChain = new TransformChain();
     m_refTarget = uri;
     m_uri = uri;
     m_refTargetType = ReferenceTargetType.UriReference;
     m_cachedXml = null;
     m_digestMethod = SignedXml.XmlDsigSHA1Url;
 }
Esempio n. 13
0
 public Reference(Stream stream)
 {
     m_transformChain = new TransformChain();
     m_refTarget      = stream;
     m_refTargetType  = ReferenceTargetType.Stream;
     m_cachedXml      = null;
     m_digestMethod   = SignedXml.XmlDsigSHA1Url;
 }
Esempio n. 14
0
        //
        // public constructors
        //

        public Reference(string uri, string tagASerAplicada, SignedXml main)
        {
            _transformChain = new TransformChain();
            _uri            = uri;
            tag             = tagASerAplicada;
            _digestMethod   = SignedXml.XmlDsigSHA1Url;
            _signedXml      = main;
        }
Esempio n. 15
0
        //
        // public constructors
        //

        public Reference()
        {
            _transformChain = new TransformChain();
            _refTarget      = null;
            _refTargetType  = ReferenceTargetType.UriReference;
            _cachedXml      = null;
            _digestMethod   = SignedXml.XmlDsigSHA1Url;
        }
Esempio n. 16
0
        //
        // public constructors
        //

        public Reference()
        {
            _transformChain = new TransformChain();
            _refTarget      = null;
            _refTargetType  = ReferenceTargetType.UriReference;
            _cachedXml      = null;
            _digestMethod   = DefaultDigestMethod;
        }
Esempio n. 17
0
 public Reference(Stream stream)
 {
     _transformChain = new TransformChain();
     _refTarget      = stream;
     _refTargetType  = ReferenceTargetType.Stream;
     _cachedXml      = null;
     _digestMethod   = DefaultDigestMethod;
 }
Esempio n. 18
0
 internal Reference(XmlElement element)
 {
     m_transformChain = new TransformChain();
     m_refTarget      = element;
     m_refTargetType  = ReferenceTargetType.XmlElement;
     m_cachedXml      = null;
     m_digestMethod   = SignedXml.XmlDsigSHA1Url;
 }
Esempio n. 19
0
 internal Reference(XmlElement element)
 {
     _transformChain = new TransformChain();
     _refTarget      = element;
     _refTargetType  = ReferenceTargetType.XmlElement;
     _cachedXml      = null;
     _digestMethod   = DefaultDigestMethod;
 }
Esempio n. 20
0
        public void AddTransform(Transform transform)
        {
            if (transform == null)
            {
                throw new ArgumentNullException(nameof(transform));
            }

            TransformChain.Add(transform);
        }
Esempio n. 21
0
 public Reference(string uri)
 {
     m_transformChain = new TransformChain();
     m_refTarget      = uri;
     m_uri            = uri;
     m_refTargetType  = ReferenceTargetType.UriReference;
     m_cachedXml      = null;
     m_digestMethod   = SignedXml.XmlDsigSHA1Url;
 }
Esempio n. 22
0
        public void AddTransform(Transform transform)
        {
            if (transform == null)
            {
                throw new ArgumentNullException("transform");
            }

            transform.Reference = this;
            TransformChain.Add(transform);
        }
Esempio n. 23
0
        internal XmlElement GetXml(XmlDocument document)
        {
            // Create the Reference
            XmlElement referenceElement = document.CreateElement("Reference", SignedXml.XmlDsigNamespaceUrl);

            if (!string.IsNullOrEmpty(_id))
            {
                referenceElement.SetAttribute("Id", _id);
            }

            if (_uri != null)
            {
                referenceElement.SetAttribute("URI", _uri);
            }

            if (!string.IsNullOrEmpty(_type))
            {
                referenceElement.SetAttribute("Type", _type);
            }

            // Add the transforms to the Reference
            if (TransformChain.Count != 0)
            {
                referenceElement.AppendChild(TransformChain.GetXml(document, SignedXml.XmlDsigNamespaceUrl));
            }

            // Add the DigestMethod
            if (string.IsNullOrEmpty(_digestMethod))
            {
                throw new CryptographicException(SR.Cryptography_Xml_DigestMethodRequired);
            }

            XmlElement digestMethodElement = document.CreateElement("DigestMethod", SignedXml.XmlDsigNamespaceUrl);

            digestMethodElement.SetAttribute("Algorithm", _digestMethod);
            referenceElement.AppendChild(digestMethodElement);

            if (DigestValue == null)
            {
                if (_hashAlgorithm.Hash == null)
                {
                    throw new CryptographicException(SR.Cryptography_Xml_DigestValueRequired);
                }
                DigestValue = _hashAlgorithm.Hash;
            }

            XmlElement digestValueElement = document.CreateElement("DigestValue", SignedXml.XmlDsigNamespaceUrl);

            digestValueElement.AppendChild(document.CreateTextNode(Convert.ToBase64String(_digestValue)));
            referenceElement.AppendChild(digestValueElement);

            return(referenceElement);
        }
Esempio n. 24
0
        private bool ReferenceUsesSafeTransformMethods(Reference reference)
        {
            TransformChain transformChain = reference.TransformChain;
            int            transformCount = transformChain.Count;

            for (int i = 0; i < transformCount; i++)
            {
                Transform transform = transformChain[i];

                if (!IsSafeTransform(transform.Algorithm))
                {
                    return(false);
                }
            }

            return(true);
        }
        /// <summary>
        ///     Verify the transforms on a strong name signature are valid for a ClickOnce manifest.
        /// </summary>
        /// <remarks>
        ///     For a reference to the entire document, we expect both exclusive cannonicalization and
        ///     enveloped transform. For a reference to the  strong name key section, we expect only exclusive
        ///     cannonicalization. Other references are not given special meaning for a strong name signature
        ///     and are ignored. Failure to have exactly the correct set of transforms is an error with the
        ///     strong name signature.
        /// </remarks>
        private static SignatureVerificationResult VerifyStrongNameSignatureTransforms(SignedInfo signedInfo)
        {
            Debug.Assert(signedInfo != null, "signedInfo != null");

            int totalReferences = 0;

            foreach (Reference reference in signedInfo.References)
            {
                TransformChain transforms          = reference.TransformChain;
                bool           validTransformChain = false;

                if (String.IsNullOrEmpty(reference.Uri))
                {
                    totalReferences++;
                    validTransformChain = transforms != null &&
                                          transforms.Count == 2 &&
                                          String.Compare(transforms[0].Algorithm, SignedXml.XmlDsigEnvelopedSignatureTransformUrl, StringComparison.Ordinal) == 0 &&
                                          String.Compare(transforms[1].Algorithm, SignedXml.XmlDsigExcC14NTransformUrl, StringComparison.Ordinal) == 0;
                }
                else if (String.Compare(reference.Uri, "#StrongNameKeyInfo", StringComparison.Ordinal) == 0)
                {
                    totalReferences++;
                    validTransformChain = transforms != null &&
                                          transforms.Count == 1 &&
                                          String.Compare(transforms[0].Algorithm, SignedXml.XmlDsigExcC14NTransformUrl, StringComparison.Ordinal) == 0;
                }
                else
                {
                    validTransformChain = true;
                }

                if (!validTransformChain)
                {
                    return(SignatureVerificationResult.BadSignatureFormat);
                }
            }

            if (totalReferences == 0)
            {
                return(SignatureVerificationResult.BadSignatureFormat);
            }

            return(SignatureVerificationResult.Valid);
        }
Esempio n. 26
0
        internal new XmlElement GetXml(XmlDocument document)
        {
            if (ReferenceType == null)
            {
                throw new CryptographicException(SR.Cryptography_Xml_ReferenceTypeRequired);
            }

            // Create the Reference
            XmlElement referenceElement = document.CreateElement(ReferenceType, EncryptedXml.XmlEncNamespaceUrl);

            if (!string.IsNullOrEmpty(Uri))
            {
                referenceElement.SetAttribute("URI", Uri);
            }

            // Add the transforms to the CipherReference
            if (TransformChain.Count > 0)
            {
                referenceElement.AppendChild(TransformChain.GetXml(document, EncryptedXml.XmlEncNamespaceUrl));
            }

            return(referenceElement);
        }
Esempio n. 27
0
        public virtual void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            ReferenceType = value.LocalName;
            Uri           = Utils.GetAttribute(value, "URI", EncryptedXml.XmlEncNamespaceUrl);

            // Transforms
            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
            XmlNode transformsNode = value.SelectSingleNode("ds:Transforms", nsm);

            if (transformsNode != null)
            {
                TransformChain.LoadXml(transformsNode as XmlElement);
            }

            // cache the Xml
            _cachedXml = value;
        }
Esempio n. 28
0
 protected EncryptedReference(string uri, TransformChain transformChain)
 {
     TransformChain = transformChain;
     Uri            = uri;
     _cachedXml     = null;
 }
Esempio n. 29
0
		public CipherReference (string uri, TransformChain tc)
			: base (uri, tc)
		{
		}
 protected EncryptedReference (string uri, TransformChain transformChain) {
     this.TransformChain = transformChain;
     this.Uri = uri;
     m_cachedXml = null;
 }
 public KeyReference (string uri, TransformChain transformChain) : base(uri, transformChain) {
     ReferenceType = "KeyReference";
 }
 public CipherReference (string uri, TransformChain transformChain) : base(uri, transformChain) {
     ReferenceType = "CipherReference";
 }
Esempio n. 33
0
 public DataReference(string uri, TransformChain tc)
     : base(uri, tc)
 {
     ReferenceType = XmlEncryption.ElementNames.DataReference;
 }
Esempio n. 34
0
		protected EncryptedReference (string uri, TransformChain tc)
			: this ()
		{
			Uri = uri;
			TransformChain = tc;
		}
Esempio n. 35
0
		public Reference () 
		{
			chain = new TransformChain ();
			digestMethod = XmlSignature.NamespaceURI + "sha1";
		}
 public KeyReference(string uri, TransformChain transformChain) : base(uri, transformChain)
 {
     base.ReferenceType = "KeyReference";
 }
 public Reference()
 {
     chain        = new TransformChain();
     digestMethod = XmlSignature.NamespaceURI + "sha1";
 }
Esempio n. 38
0
		public KeyReference (string uri, TransformChain tc)
			: base (uri, tc)
		{
			ReferenceType = XmlEncryption.ElementNames.KeyReference;
		}
 protected EncryptedReference(string uri, TransformChain transformChain)
 {
     this.TransformChain = transformChain;
     this.Uri            = uri;
     m_cachedXml         = null;
 }
Esempio n. 40
0
 public DataReference(string uri, TransformChain transformChain) : base(uri, transformChain)
 {
     ReferenceType = "DataReference";
 }
Esempio n. 41
0
        public void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            _id   = Utils.GetAttribute(value, "Id", SignedXml.XmlDsigNamespaceUrl);
            _uri  = Utils.GetAttribute(value, "URI", SignedXml.XmlDsigNamespaceUrl);
            _type = Utils.GetAttribute(value, "Type", SignedXml.XmlDsigNamespaceUrl);
            if (!Utils.VerifyAttributes(value, new string[] { "Id", "URI", "Type" }))
            {
                throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference");
            }

            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);

            // Transforms
            bool hasTransforms = false;

            TransformChain = new TransformChain();
            XmlNodeList transformsNodes = value.SelectNodes("ds:Transforms", nsm);

            if (transformsNodes != null && transformsNodes.Count != 0)
            {
                if (transformsNodes.Count > 1)
                {
                    throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/Transforms");
                }
                hasTransforms = true;
                XmlElement transformsElement = transformsNodes[0] as XmlElement;
                if (!Utils.VerifyAttributes(transformsElement, (string[])null))
                {
                    throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/Transforms");
                }
                XmlNodeList transformNodes = transformsElement.SelectNodes("ds:Transform", nsm);
                if (transformNodes != null)
                {
                    if (transformNodes.Count != transformsElement.SelectNodes("*").Count)
                    {
                        throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/Transforms");
                    }
                    if (transformNodes.Count > Utils.MaxTransformsPerReference)
                    {
                        throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/Transforms");
                    }
                    foreach (XmlNode transformNode in transformNodes)
                    {
                        XmlElement transformElement = transformNode as XmlElement;
                        string     algorithm        = Utils.GetAttribute(transformElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);
                        if (algorithm == null || !Utils.VerifyAttributes(transformElement, "Algorithm"))
                        {
                            throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform);
                        }
                        Transform transform = CryptoHelpers.CreateFromName <Transform>(algorithm);
                        if (transform == null)
                        {
                            throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform);
                        }
                        AddTransform(transform);
                        // let the transform read the children of the transformElement for data
                        transform.LoadInnerXml(transformElement.ChildNodes);
                        // Hack! this is done to get around the lack of here() function support in XPath
                        if (transform is XmlDsigEnvelopedSignatureTransform)
                        {
                            // Walk back to the Signature tag. Find the nearest signature ancestor
                            // Signature-->SignedInfo-->Reference-->Transforms-->Transform
                            XmlNode     signatureTag  = transformElement.SelectSingleNode("ancestor::ds:Signature[1]", nsm);
                            XmlNodeList signatureList = transformElement.SelectNodes("//ds:Signature", nsm);
                            if (signatureList != null)
                            {
                                int position = 0;
                                foreach (XmlNode node in signatureList)
                                {
                                    position++;
                                    if (node == signatureTag)
                                    {
                                        ((XmlDsigEnvelopedSignatureTransform)transform).SignaturePosition = position;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // DigestMethod
            XmlNodeList digestMethodNodes = value.SelectNodes("ds:DigestMethod", nsm);

            if (digestMethodNodes == null || digestMethodNodes.Count == 0 || digestMethodNodes.Count > 1)
            {
                throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestMethod");
            }
            XmlElement digestMethodElement = digestMethodNodes[0] as XmlElement;

            _digestMethod = Utils.GetAttribute(digestMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);
            if (_digestMethod == null || !Utils.VerifyAttributes(digestMethodElement, "Algorithm"))
            {
                throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestMethod");
            }


            // DigestValue
            XmlNodeList digestValueNodes = value.SelectNodes("ds:DigestValue", nsm);

            if (digestValueNodes == null || digestValueNodes.Count == 0 || digestValueNodes.Count > 1)
            {
                throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestValue");
            }
            XmlElement digestValueElement = digestValueNodes[0] as XmlElement;

            _digestValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(digestValueElement.InnerText));
            if (!Utils.VerifyAttributes(digestValueElement, (string[])null))
            {
                throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestValue");
            }
            // Verify that there aren't any extra nodes that aren't allowed
            int expectedChildNodeCount = hasTransforms ? 3 : 2;

            if (value.SelectNodes("*").Count != expectedChildNodeCount)
            {
                throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference");
            }

            // cache the Xml
            _cachedXml = value;
        }
 public DataReference(string uri, TransformChain transformChain) : base(uri, transformChain)
 {
     base.ReferenceType = "DataReference";
 }
Esempio n. 43
0
        // 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);
        }
Esempio n. 44
0
		public virtual void LoadXml (XmlElement value)
		{
			if (value == null)
				throw new ArgumentNullException ("value");
			else {
				Uri = null;
				TransformChain = new TransformChain ();

				foreach (XmlNode n in value.ChildNodes) {
					if (n is XmlWhitespace)
						continue;

					switch (n.LocalName) {
					case XmlEncryption.ElementNames.Transforms:
						foreach (XmlNode xn in ((XmlElement) n).GetElementsByTagName (XmlSignature.ElementNames.Transform, XmlSignature.NamespaceURI)) {
							Transform t = null;
							switch (((XmlElement) xn).Attributes [XmlSignature.AttributeNames.Algorithm].Value) {
							case XmlSignature.AlgorithmNamespaces.XmlDsigBase64Transform:
								t = new XmlDsigBase64Transform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigC14NTransform:
								t = new XmlDsigC14NTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigC14NWithCommentsTransform:
								t = new XmlDsigC14NWithCommentsTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigEnvelopedSignatureTransform:
								t = new XmlDsigEnvelopedSignatureTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigXPathTransform:
								t = new XmlDsigXPathTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigXsltTransform:
								t = new XmlDsigXsltTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigExcC14NTransform:
								t = new XmlDsigExcC14NTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigExcC14NWithCommentsTransform:
								t = new XmlDsigExcC14NWithCommentsTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDecryptionTransform:
								t = new XmlDecryptionTransform ();
								break;
							default:
								continue;
							}

							t.LoadInnerXml (((XmlElement) xn).ChildNodes);
							TransformChain.Add (t);
						}
						break;
					}
				}

				if (value.HasAttribute (XmlEncryption.AttributeNames.URI))
					Uri = value.Attributes [XmlEncryption.AttributeNames.URI].Value;
			}
		}
Esempio n. 45
0
		protected EncryptedReference (string uri)
		{
			Uri = uri;
			TransformChain = new TransformChain ();
		}
		public override void LoadXml (XmlElement value)
		{
			if (value == null)
				throw new ArgumentNullException ("value");
			if ((value.LocalName != XmlEncryption.ElementNames.CipherReference) || (value.NamespaceURI != EncryptedXml.XmlEncNamespaceUrl))
				throw new CryptographicException ("Malformed CipherReference element.");
			else {
				Uri = null;
				TransformChain = new TransformChain ();

				foreach (XmlNode n in value.ChildNodes) {
					if (n is XmlWhitespace)
						continue;

					switch (n.LocalName) {
					case XmlEncryption.ElementNames.Transforms:
						foreach (XmlNode xn in ((XmlElement) n).GetElementsByTagName (XmlSignature.ElementNames.Transform, XmlSignature.NamespaceURI)) {
							Transform t = null;
							switch (((XmlElement) xn).Attributes [XmlSignature.AttributeNames.Algorithm].Value) {
							case XmlSignature.AlgorithmNamespaces.XmlDsigBase64Transform:
								t = new XmlDsigBase64Transform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigC14NTransform:
								t = new XmlDsigC14NTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigC14NWithCommentsTransform:
								t = new XmlDsigC14NWithCommentsTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigEnvelopedSignatureTransform:
								t = new XmlDsigEnvelopedSignatureTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigXPathTransform:
								t = new XmlDsigXPathTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigXsltTransform:
								t = new XmlDsigXsltTransform ();
								break;
#if NET_2_0
							case XmlSignature.AlgorithmNamespaces.XmlDecryptionTransform:
								t = new XmlDecryptionTransform ();
								break;
#endif
							default:
								continue;
							}

							t.LoadInnerXml (((XmlElement) xn).ChildNodes);
							TransformChain.Add (t);
						}
						break;
					}
				}
						
				if (value.HasAttribute (XmlEncryption.AttributeNames.URI))
					Uri = value.Attributes [XmlEncryption.AttributeNames.URI].Value;
			}
		}
Esempio n. 47
0
 public CipherReference(string uri, TransformChain transformChain) : base(uri, transformChain)
 {
     ReferenceType = "CipherReference";
 }
Esempio n. 48
0
		protected EncryptedReference ()
		{
			TransformChain = new TransformChain ();
		}
		protected EncryptedReference ()
		{
			uri = null;
			TransformChain = new TransformChain ();
		}
Esempio n. 50
0
        //
        // private methods
        //

        private byte[] GetCipherValue(CipherData cipherData)
        {
            if (cipherData == null)
            {
                throw new ArgumentNullException("cipherData");
            }

            WebResponse response    = null;
            Stream      inputStream = null;

            if (cipherData.CipherValue != null)
            {
                return(cipherData.CipherValue);
            }
            else if (cipherData.CipherReference != null)
            {
                if (cipherData.CipherReference.CipherValue != null)
                {
                    return(cipherData.CipherReference.CipherValue);
                }
                Stream decInputStream = null;
                // See if the CipherReference is a local URI
                if (!Utils.GetLeaveCipherValueUnchecked() && cipherData.CipherReference.Uri == null)
                {
                    throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotSupported"));
                }
                if (cipherData.CipherReference.Uri.Length == 0)
                {
                    // self referenced Uri
                    string         baseUri = (m_document == null ? null : m_document.BaseURI);
                    TransformChain tc      = cipherData.CipherReference.TransformChain;
                    if (!Utils.GetLeaveCipherValueUnchecked() && tc == null)
                    {
                        throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotSupported"));
                    }
                    decInputStream = tc.TransformToOctetStream(m_document, m_xmlResolver, baseUri);
                }
                else if (cipherData.CipherReference.Uri[0] == '#')
                {
                    string idref = Utils.ExtractIdFromLocalUri(cipherData.CipherReference.Uri);
                    // Serialize
                    if (Utils.GetLeaveCipherValueUnchecked())
                    {
                        inputStream = new MemoryStream(m_encoding.GetBytes(GetIdElement(m_document, idref).OuterXml));
                    }
                    else
                    {
                        XmlElement idElem = GetIdElement(m_document, idref);
                        if (idElem == null || idElem.OuterXml == null)
                        {
                            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotSupported"));
                        }
                        inputStream = new MemoryStream(m_encoding.GetBytes(idElem.OuterXml));
                    }

                    string         baseUri = (m_document == null ? null : m_document.BaseURI);
                    TransformChain tc      = cipherData.CipherReference.TransformChain;
                    if (!Utils.GetLeaveCipherValueUnchecked() && tc == null)
                    {
                        throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotSupported"));
                    }
                    decInputStream = tc.TransformToOctetStream(inputStream, m_xmlResolver, baseUri);
                }
                else
                {
                    DownloadCipherValue(cipherData, out inputStream, out decInputStream, out response);
                }
                // read the output stream into a memory stream
                byte[] cipherValue = null;
                using (MemoryStream ms = new MemoryStream()) {
                    Utils.Pump(decInputStream, ms);
                    cipherValue = ms.ToArray();
                    // Close the stream and return
                    if (response != null)
                    {
                        response.Close();
                    }
                    if (inputStream != null)
                    {
                        inputStream.Close();
                    }
                    decInputStream.Close();
                }

                // cache the cipher value for Perf reasons in case we call this routine twice
                cipherData.CipherReference.CipherValue = cipherValue;
                return(cipherValue);
            }

            // Throw a CryptographicException if we were unable to retrieve the cipher data.
            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingCipherData"));
        }