public override void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

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

            if (uri == null)
            {
                throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_UriRequired);
            }
            Uri = uri;

            // 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;
        }
Пример #2
0
        private XmlElement GetXml1(XmlDocument document)
        {
            XmlElement referenceElement = document.CreateElement("Reference", XmlNameSpace.Url[NS.XmlDsigNamespaceUrl]);

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

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

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

            if (TransformChain.Count != 0)
            {
                referenceElement.AppendChild(TransformChain.GetXml(document, NS.XmlDsigNamespaceUrl));
            }

            if (string.IsNullOrEmpty(_digestMethod))
            {
                throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_DigestMethodRequired);
            }
            return(referenceElement);
        }
        public virtual void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            ReferenceType = value.LocalName;

            string uri = ElementUtils.GetAttribute(value, "URI", NS.XmlEncNamespaceUrl);

            if (uri == null)
            {
                throw new ArgumentNullException(SR.Cryptography_Xml_UriRequired);
            }
            Uri = uri;

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

            nsm.AddNamespace("ds", XmlNameSpace.Url[NS.XmlDsigNamespaceUrl]);
            XmlNode transformsNode = value.SelectSingleNode("ds:Transforms", nsm);

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

            _cachedXml = value;
        }
Пример #4
0
 public Reference(Stream stream)
 {
     _transformChain = new TransformChain();
     _refTarget      = stream;
     _refTargetType  = ReferenceTargetType.Stream;
     _cachedXml      = null;
     _digestMethod   = DefaultDigestMethod;
 }
Пример #5
0
 internal Reference(XmlElement element)
 {
     _transformChain = new TransformChain();
     _refTarget      = element;
     _refTargetType  = ReferenceTargetType.XmlElement;
     _cachedXml      = null;
     _digestMethod   = DefaultDigestMethod;
 }
Пример #6
0
 internal Reference(XmlElement element)
 {
     _transformChain = new TransformChain();
     _refTarget      = element;
     _refTargetType  = ReferenceTargetType.XmlElement;
     _cachedXml      = null;
     _digestMethod   = XmlNameSpace.Url[NS.XmlDsigSHA256Url];
 }
Пример #7
0
 public Reference(Stream stream)
 {
     _transformChain = new TransformChain();
     _refTarget      = stream;
     _refTargetType  = ReferenceTargetType.Stream;
     _cachedXml      = null;
     _digestMethod   = XmlNameSpace.Url[NS.XmlDsigSHA256Url];
 }
Пример #8
0
        //
        // public constructors
        //

        public Reference()
        {
            _transformChain = new TransformChain();
            _refTarget      = null;
            _refTargetType  = ReferenceTargetType.UriReference;
            _cachedXml      = null;
            _digestMethod   = DefaultDigestMethod;
        }
Пример #9
0
 public Reference(string uri)
 {
     _transformChain = new TransformChain();
     _refTarget      = uri;
     _uri            = uri;
     _refTargetType  = ReferenceTargetType.UriReference;
     _cachedXml      = null;
     _digestMethod   = XmlNameSpace.Url[NS.XmlDsigSHA256Url];
 }
Пример #10
0
        public void AddTransform(Transform transform)
        {
            if (transform == null)
            {
                throw new ArgumentNullException(nameof(transform));
            }

            transform.Reference = this;
            TransformChain.Add(transform);
        }
Пример #11
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 System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_DigestMethodRequired);
            }

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

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

            if (DigestValue == null)
            {
                if (_hashval == null)
                {
                    throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_DigestValueRequired);
                }
                DigestValue = _hashval;
            }

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

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

            return(referenceElement);
        }
        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);
        }
        internal XmlElement GetXml(XmlDocument document)
        {
            if (ReferenceType == null)
            {
                throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_ReferenceTypeRequired);
            }

            XmlElement referenceElement = document.CreateElement(ReferenceType, XmlNameSpace.Url[NS.XmlEncNamespaceUrl]);

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

            if (TransformChain.Count > 0)
            {
                referenceElement.AppendChild(TransformChain.GetXml(document, NS.XmlDsigNamespaceUrl));
            }

            return(referenceElement);
        }
        new internal XmlElement GetXml(XmlDocument document)
        {
            if (ReferenceType == null)
            {
                throw new System.Security.Cryptography.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);
        }
Пример #15
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;
        }
Пример #16
0
        public void LoadXml(XmlElement value)
        {
            LoadXml1(value);

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

            nsm.AddNamespace("ds", XmlNameSpace.Url[NS.XmlDsigNamespaceUrl]);

            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 System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/Transforms");
                }
                hasTransforms = true;
                XmlElement transformsElement = transformsNodes[0] as XmlElement;
                if (!ElementUtils.VerifyAttributes(transformsElement, (string[])null))
                {
                    throw new System.Security.Cryptography.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 System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/Transforms");
                    }
                    if (transformNodes.Count > CryptoUtils.MaxTransformsPerReference)
                    {
                        throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/Transforms");
                    }
                    foreach (XmlNode transformNode in transformNodes)
                    {
                        XmlElement transformElement = transformNode as XmlElement;
                        string     algorithm        = ElementUtils.GetAttribute(transformElement, "Algorithm", NS.XmlDsigNamespaceUrl);
                        if (algorithm == null || !ElementUtils.VerifyAttributes(transformElement, "Algorithm"))
                        {
                            throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_UnknownTransform);
                        }
                        Transform transform = CryptoHelpers.CreateFromName <Transform>(algorithm);
                        if (transform == null)
                        {
                            throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_UnknownTransform);
                        }
                        AddTransform(transform);
                        transform.LoadInnerXml(transformElement.ChildNodes);
                        if (transform is XmlDsigEnvelopedSignatureTransform)
                        {
                            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;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            LoadXml2(value, nsm, hasTransforms);
        }
 public KeyReference(string uri, TransformChain transformChain) : base(uri, transformChain)
 {
     ReferenceType = "KeyReference";
 }
 public CipherReference(string uri, TransformChain transformChain) : base(uri, transformChain)
 {
     ReferenceType = "CipherReference";
 }
Пример #19
0
        internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList)
        {
            IDigest digest = CryptoHelpers.CreateFromName <IDigest>(_digestMethod);

            if (digest == null)
            {
                IMac mac = CryptoHelpers.CreateFromName <IMac>(_digestMethod);
                if (mac == null)
                {
                    throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed);
                }

                byte[] randomKey = CryptoUtils.GenerateRandomBlock(mac.GetMacSize());
                mac.Init(new KeyParameter(randomKey));

                _hashAlgorithm = new MacHashWrapper(mac);
            }
            else
            {
                _hashAlgorithm = new DigestHashWrapper(digest);
            }

            string      baseUri         = document == null ? Environment.CurrentDirectory + "\\" : document.BaseURI;
            Stream      hashInputStream = null;
            WebResponse response        = null;
            Stream      inputStream     = null;
            XmlResolver resolver        = null;

            _hashval = null;

            try
            {
                switch (_refTargetType)
                {
                case ReferenceTargetType.Stream:
                    resolver        = (GetSignedXml().ResolverSet ? GetSignedXml()._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                    hashInputStream = TransformChain.TransformToOctetStream((Stream)_refTarget, resolver, baseUri);
                    break;

                case ReferenceTargetType.UriReference:
                    if (_uri == null)
                    {
                        resolver        = (GetSignedXml().ResolverSet ? GetSignedXml()._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                        hashInputStream = TransformChain.TransformToOctetStream((Stream)null, resolver, baseUri);
                    }
                    else if (_uri.Length == 0)
                    {
                        if (document == null)
                        {
                            throw new System.Security.Cryptography.CryptographicException(string.Format(CultureInfo.CurrentCulture, SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri));
                        }

                        resolver = (GetSignedXml().ResolverSet ? GetSignedXml()._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                        XmlDocument docWithNoComments = StreamUtils.DiscardComments(StreamUtils.PreProcessDocumentInput(document, resolver, baseUri));
                        hashInputStream = TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri);
                    }
                    else if (_uri[0] == '#')
                    {
                        bool   discardComments = true;
                        string idref           = ParserUtils.GetIdFromLocalUri(_uri, out discardComments);
                        if (idref == "xpointer(/)")
                        {
                            if (document == null)
                            {
                                throw new System.Security.Cryptography.CryptographicException(string.Format(CultureInfo.CurrentCulture, SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri));
                            }

                            resolver        = (GetSignedXml().ResolverSet ? GetSignedXml()._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                            hashInputStream = TransformChain.TransformToOctetStream(StreamUtils.PreProcessDocumentInput(document, resolver, baseUri), resolver, baseUri);
                            break;
                        }

                        XmlElement elem = GetSignedXml().GetIdElement(document, idref);
                        if (elem != null)
                        {
                            _namespaces = ElementUtils.GetPropagatedAttributes(elem.ParentNode as XmlElement);
                        }

                        if (elem == null && refList != null)
                        {
                            foreach (XmlNode node in refList)
                            {
                                XmlElement tempElem = node as XmlElement;
                                if ((tempElem != null) && (ElementUtils.HasAttribute(tempElem, "Id", XmlNameSpace.Url[NS.XmlDsigNamespaceUrl])) &&
                                    (ElementUtils.GetAttribute(tempElem, "Id", NS.XmlDsigNamespaceUrl).Equals(idref)))
                                {
                                    elem = tempElem;
                                    if (_signedXml._context != null)
                                    {
                                        _namespaces = ElementUtils.GetPropagatedAttributes(_signedXml._context);
                                    }
                                    break;
                                }
                            }
                        }

                        if (elem == null)
                        {
                            throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_InvalidReference);
                        }

                        XmlDocument normDocument = StreamUtils.PreProcessElementInput(elem, resolver, baseUri);
                        ElementUtils.AddNamespaces(normDocument.DocumentElement, _namespaces);

                        resolver = (GetSignedXml().ResolverSet ? GetSignedXml()._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                        if (discardComments)
                        {
                            XmlDocument docWithNoComments = StreamUtils.DiscardComments(normDocument);
                            hashInputStream = TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri);
                        }
                        else
                        {
                            hashInputStream = TransformChain.TransformToOctetStream(normDocument, resolver, baseUri);
                        }
                    }
                    else
                    {
                        throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_UriNotResolved, _uri);
                    }
                    break;

                case ReferenceTargetType.XmlElement:
                    resolver        = (GetSignedXml().ResolverSet ? GetSignedXml()._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                    hashInputStream = TransformChain.TransformToOctetStream(StreamUtils.PreProcessElementInput((XmlElement)_refTarget, resolver, baseUri), resolver, baseUri);
                    break;

                default:
                    throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_UriNotResolved, _uri);
                }

                hashInputStream = SignedXmlDebugLog.LogReferenceData(this, hashInputStream);
                byte[] buffer = new byte[4096];
                int    bytesRead;
                _hashAlgorithm.Reset();
                while ((bytesRead = hashInputStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    _hashAlgorithm.BlockUpdate(buffer, 0, bytesRead);
                }
                _hashval = new byte[_hashAlgorithm.GetHashSize()];
                _hashAlgorithm.DoFinal(_hashval, 0);
            }
            finally
            {
                if (hashInputStream != null)
                {
                    hashInputStream.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
                if (inputStream != null)
                {
                    inputStream.Close();
                }
            }

            return(_hashval);
        }
Пример #20
0
        public void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            _id   = Utils.GetAttribute(value, "Id", SignedXml.XmlDsigNamespaceUrl);
            _uri  = Utils.GetAttribute(value, "URI", SignedXml.XmlDsigNamespaceUrl);
            _type = Utils.GetAttribute(value, "Type", SignedXml.XmlDsigNamespaceUrl);

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

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

            // Transforms
            TransformChain = new TransformChain();
            XmlElement transformsElement = value.SelectSingleNode("ds:Transforms", nsm) as XmlElement;

            if (transformsElement != null)
            {
                XmlNodeList transformNodes = transformsElement.SelectNodes("ds:Transform", nsm);
                if (transformNodes != null)
                {
                    foreach (XmlNode transformNode in transformNodes)
                    {
                        XmlElement transformElement = transformNode as XmlElement;
                        string     algorithm        = Utils.GetAttribute(transformElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);
                        Transform  transform        = CryptoHelpers.CreateFromName(algorithm) as Transform;
                        if (transform == null)
                        {
                            throw new System.Security.Cryptography.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
            XmlElement digestMethodElement = value.SelectSingleNode("ds:DigestMethod", nsm) as XmlElement;

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

            // DigestValue
            XmlElement digestValueElement = value.SelectSingleNode("ds:DigestValue", nsm) as XmlElement;

            if (digestValueElement == null)
            {
                throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestValue");
            }
            _digestValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(digestValueElement.InnerText));

            // cache the Xml
            _cachedXml = value;
        }
Пример #21
0
        //
        // private methods
        //

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

            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;
                if (cipherData.CipherReference.Uri == null)
                {
                    throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_UriNotSupported);
                }
                // See if the CipherReference is a local URI
                if (cipherData.CipherReference.Uri.Length == 0)
                {
                    // self referenced Uri
                    string         baseUri = (_document == null ? null : _document.BaseURI);
                    TransformChain tc      = cipherData.CipherReference.TransformChain;
                    if (tc == null)
                    {
                        throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_UriNotSupported);
                    }
                    decInputStream = tc.TransformToOctetStream(_document, _xmlResolver, baseUri);
                }
                else if (cipherData.CipherReference.Uri[0] == '#')
                {
                    string idref = Utils.ExtractIdFromLocalUri(cipherData.CipherReference.Uri);
                    // Serialize
                    XmlElement idElem = GetIdElement(_document, idref);
                    if (idElem == null || idElem.OuterXml == null)
                    {
                        throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_UriNotSupported);
                    }
                    inputStream = new MemoryStream(_encoding.GetBytes(idElem.OuterXml));
                    string         baseUri = (_document == null ? null : _document.BaseURI);
                    TransformChain tc      = cipherData.CipherReference.TransformChain;
                    if (tc == null)
                    {
                        throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_UriNotSupported);
                    }
                    decInputStream = tc.TransformToOctetStream(inputStream, _xmlResolver, baseUri);
                }
                else
                {
                    throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_UriNotResolved, cipherData.CipherReference.Uri);
                }
                // 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 (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 System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_MissingCipherData);
        }
Пример #22
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
            IDigest digest = CryptoHelpers.CreateFromName <IDigest>(_digestMethod);

            if (digest == null)
            {
                IMac mac = CryptoHelpers.CreateFromName <IMac>(_digestMethod);
                if (mac == null)
                {
                    throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed);
                }

                // For compatibility to corefx' HMAC implementation
                byte[] randomKey = Utils.GenerateRandomBlock(mac.GetMacSize());
                mac.Init(new KeyParameter(randomKey));

                _hashAlgorithm = new MacHashWrapper(mac);
            }
            else
            {
                _hashAlgorithm = new DigestHashWrapper(digest);
            }

            // 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;

            _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 System.Security.Cryptography.CryptographicException(string.Format(CultureInfo.CurrentCulture, 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 System.Security.Cryptography.CryptographicException(string.Format(CultureInfo.CurrentCulture, 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 System.Security.Cryptography.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 System.Security.Cryptography.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 System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_UriNotResolved, _uri);
                }

                // Compute the new hash value
                hashInputStream = SignedXmlDebugLog.LogReferenceData(this, hashInputStream);
                // Default the buffer size to 4K.
                byte[] buffer = new byte[4096];
                int    bytesRead;
                _hashAlgorithm.Reset();
                while ((bytesRead = hashInputStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    _hashAlgorithm.BlockUpdate(buffer, 0, bytesRead);
                }
                _hashval = new byte[_hashAlgorithm.GetHashSize()];
                _hashAlgorithm.DoFinal(_hashval, 0);
            }
            finally
            {
                if (hashInputStream != null)
                {
                    hashInputStream.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
                if (inputStream != null)
                {
                    inputStream.Close();
                }
            }

            return(_hashval);
        }
 protected EncryptedReference(string uri, TransformChain transformChain)
 {
     TransformChain = transformChain;
     Uri            = uri;
     _cachedXml     = null;
 }
Пример #24
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 System.Security.Cryptography.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 System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/Transforms");
                }
                hasTransforms = true;
                XmlElement transformsElement = transformsNodes[0] as XmlElement;
                if (!Utils.VerifyAttributes(transformsElement, (string[])null))
                {
                    throw new System.Security.Cryptography.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 System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/Transforms");
                    }
                    if (transformNodes.Count > Utils.MaxTransformsPerReference)
                    {
                        throw new System.Security.Cryptography.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 System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_UnknownTransform);
                        }
                        Transform transform = CryptoHelpers.CreateFromName <Transform>(algorithm);
                        if (transform == null)
                        {
                            throw new System.Security.Cryptography.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 System.Security.Cryptography.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 System.Security.Cryptography.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 System.Security.Cryptography.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 System.Security.Cryptography.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 System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference");
            }

            // cache the Xml
            _cachedXml = value;
        }