/// <summary>
        /// Releases the unmanaged resources used by the System.IdentityModel.Protocols.XmlSignature.EnvelopedSignatureWriter and optionally
        /// releases the managed resources.
        /// </summary>
        /// <param name="disposing">
        /// True to release both managed and unmanaged resources; false to release only unmanaged resources.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (_disposed)
            {
                return;
            }

            if (disposing)
            {
                //
                // Free all of our managed resources
                //
                if (_hashStream != null)
                {
                    _hashStream.Dispose();
                    _hashStream = null;
                }

                if (_hashAlgorithm != null)
                {
                    ((IDisposable)_hashAlgorithm).Dispose();
                    _hashAlgorithm = null;
                }

                if (_signatureFragment != null)
                {
                    _signatureFragment.Dispose();
                    _signatureFragment = null;
                }

                if (_endFragment != null)
                {
                    _endFragment.Dispose();
                    _endFragment = null;
                }

                if (_writerStream != null)
                {
                    _writerStream.Dispose();
                    _writerStream = null;
                }

                if (_preCanonicalTracingStream != null)
                {
                    _preCanonicalTracingStream.Dispose();
                    _preCanonicalTracingStream = null;
                }
            }

            // Free native resources, if any.

            _disposed = true;
        }
Пример #2
0
        public void ComputeHash(HashAlgorithm algorithm)
        {
            if (this.CanonicalizationMethod != "http://www.w3.org/2001/10/xml-exc-c14n#")
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("UnsupportedTransformAlgorithm")));
            }
            HashStream hashStream = this.ResourcePool.TakeHashStream(algorithm);

            this.ComputeHash(hashStream);
            hashStream.FlushHash();
        }
 protected override void ComputeHash(HashStream hashStream)
 {
     if (this.AddEnvelopedSignatureTransform)
     {
         base.ComputeHash(hashStream);
     }
     else
     {
         SignedInfoCanonicalFormWriter.Instance.WriteSignedInfoCanonicalForm(hashStream, base.SignatureMethod, this.DigestMethod, this.references, this.count, base.ResourcePool.TakeEncodingBuffer(), base.ResourcePool.TakeBase64Buffer());
     }
 }
 protected override void ComputeHash(HashStream hashStream)
 {
     if (this.AddEnvelopedSignatureTransform)
     {
         base.ComputeHash(hashStream);
     }
     else
     {
         SignedInfoCanonicalFormWriter.Instance.WriteSignedInfoCanonicalForm(hashStream, base.SignatureMethod, this.DigestMethod, this.references, this.count, base.ResourcePool.TakeEncodingBuffer(), base.ResourcePool.TakeBase64Buffer());
     }
 }
 public HashStream TakeHashStream(HashAlgorithm hash)
 {
     if (this.hashStream == null)
     {
         this.hashStream = new HashStream(hash);
     }
     else
     {
         this.hashStream.Reset(hash);
     }
     return this.hashStream;
 }
 private HashStream TakeHashStream(HashAlgorithm hash)
 {
     if (_hashStream == null)
     {
         _hashStream = new HashStream(hash);
     }
     else
     {
         _hashStream.Reset(hash);
     }
     return(_hashStream);
 }
 public HashStream TakeHashStream(HashAlgorithm hash)
 {
     if (this.hashStream == null)
     {
         this.hashStream = new HashStream(hash);
     }
     else
     {
         this.hashStream.Reset(hash);
     }
     return(this.hashStream);
 }
        /// <summary>
        /// Initializes an instance of <see cref="EnvelopedSignatureWriter"/>. The returned writer can be directly used
        /// to write the envelope. The signature will be automatically generated when
        /// the envelope is completed.
        /// </summary>
        /// <param name="innerWriter">Writer to wrap/</param>
        /// <param name="signingCredentials">SigningCredentials to be used to generate the signature.</param>
        /// <param name="referenceId">The reference Id of the envelope.</param>
        /// <param name="securityTokenSerializer">SecurityTokenSerializer to serialize the signature KeyInfo.</param>
        /// <exception cref="ArgumentNullException">One of he input parameter is null.</exception>
        /// <exception cref="ArgumentException">The string 'referenceId' is either null or empty.</exception>
        public EnvelopedSignatureWriter(XmlWriter innerWriter, SigningCredentials signingCredentials, string referenceId, SecurityTokenSerializer securityTokenSerializer)
        {
            if (innerWriter == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("innerWriter");
            }

            if (signingCredentials == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("signingCredentials");
            }

            if (string.IsNullOrEmpty(referenceId))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.ID0006), "referenceId"));
            }

            if (securityTokenSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenSerializer");
            }

            // Remember the user's writer here. We need to finally write out the signed XML
            // into this writer.
            _dictionaryManager = new DictionaryManager();
            _innerWriter       = innerWriter;
            _signingCreds      = signingCredentials;
            _referenceId       = referenceId;
            _tokenSerializer   = securityTokenSerializer;

            _signatureFragment = new MemoryStream();
            _endFragment       = new MemoryStream();
            _writerStream      = new MemoryStream();

            XmlDictionaryWriter effectiveWriter = XmlDictionaryWriter.CreateTextWriter(_writerStream, Encoding.UTF8, false);

            // Initialize the base writer to the newly created writer. The user should write the XML
            // to this.
            base.InitializeInnerWriter(effectiveWriter);
            _hashAlgorithm = CryptoHelper.CreateHashAlgorithm(_signingCreds.DigestAlgorithm);
            _hashStream    = new HashStream(_hashAlgorithm);
            base.InnerWriter.StartCanonicalization(_hashStream, false, null);

            //
            // Add tracing for the un-canonicalized bytes
            //
            if (DiagnosticUtility.ShouldTraceVerbose)
            {
                _preCanonicalTracingStream = new MemoryStream();
                base.InitializeTracingWriter(new XmlTextWriter(_preCanonicalTracingStream, Encoding.UTF8));
            }
        }
        private void ComputeSignature()
        {
            PreDigestedSignedInfo signedInfo = new PreDigestedSignedInfo(_dictionaryManager);

            signedInfo.AddEnvelopedSignatureTransform = true;
            signedInfo.CanonicalizationMethod         = XD.ExclusiveC14NDictionary.Namespace.Value;
            signedInfo.SignatureMethod = _signingCreds.SignatureAlgorithm;
            signedInfo.DigestMethod    = _signingCreds.DigestAlgorithm;
            signedInfo.AddReference(_referenceId, _hashStream.FlushHashAndGetValue(_preCanonicalTracingStream));

            SignedXml signedXml = new SignedXml(signedInfo, _dictionaryManager, _tokenSerializer);

            signedXml.ComputeSignature(_signingCreds.SigningKey);
            signedXml.Signature.KeyIdentifier = _signingCreds.SigningKeyIdentifier;
            signedXml.WriteTo(base.InnerWriter);
            ((IDisposable)_hashStream).Dispose();
            _hashStream = null;
        }
Пример #10
0
        public void ProcessAndDigest(object input, SignatureResourcePool resourcePool, HashAlgorithm hash, DictionaryManager dictionaryManger)
        {
            HashStream hashStream = resourcePool.TakeHashStream(hash);
            XmlReader  reader     = input as XmlReader;

            if (reader != null)
            {
                this.ProcessReaderInput(reader, resourcePool, hashStream);
            }
            else
            {
                if (!(input is ISecurityElement))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("UnsupportedInputTypeForTransform", new object[] { input.GetType() })));
                }
                XmlDictionaryWriter writer = resourcePool.TakeUtf8Writer();
                writer.StartCanonicalization(hashStream, this.IncludeComments, this.GetInclusivePrefixes());
                (input as ISecurityElement).WriteTo(writer, dictionaryManger);
                writer.EndCanonicalization();
            }
            hashStream.FlushHash();
        }
 protected override ISignatureValueSecurityElement CompletePrimarySignatureCore(SendSecurityHeaderElement[] signatureConfirmations, SecurityToken[] signedEndorsingTokens, SecurityToken[] signedTokens, SendSecurityHeaderElement[] basicTokens)
 {
     ISignatureValueSecurityElement signedXml;
     if (this.signedXml == null)
     {
         return null;
     }
     SecurityTimestamp timestamp = base.Timestamp;
     if (timestamp != null)
     {
         if (timestamp.Id == null)
         {
             throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("TimestampToSignHasNoId")));
         }
         HashStream stream = this.TakeHashStream();
         base.StandardsManager.WSUtilitySpecificationVersion.WriteTimestampCanonicalForm(stream, timestamp, this.signedInfo.ResourcePool.TakeEncodingBuffer());
         this.signedInfo.AddReference(timestamp.Id, stream.FlushHashAndGetValue());
     }
     if ((base.ShouldSignToHeader && (this.signatureKey is AsymmetricSecurityKey)) && (base.Version.Addressing != AddressingVersion.None))
     {
         if (this.toHeaderHash == null)
         {
             throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("TransportSecurityRequireToHeader")));
         }
         this.signedInfo.AddReference(this.toHeaderId, this.toHeaderHash);
     }
     this.AddSignatureReference(signatureConfirmations);
     if (base.RequireMessageProtection)
     {
         this.AddSignatureReference(signedEndorsingTokens);
         this.AddSignatureReference(signedTokens);
         this.AddSignatureReference(basicTokens);
     }
     if (this.signedInfo.ReferenceCount == 0)
     {
         throw TraceUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("NoPartsOfMessageMatchedPartsToSign")), base.Message);
     }
     try
     {
         this.signedXml.ComputeSignature(this.signatureKey);
         signedXml = this.signedXml;
     }
     finally
     {
         this.hashStream = null;
         this.signedInfo = null;
         this.signedXml = null;
         this.signatureKey = null;
         this.effectiveSignatureParts = null;
     }
     return signedXml;
 }
Пример #12
0
        internal void WriteTo(XmlWriter writer, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer)
        {
            if (writer == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");

            if ((this.signingCredentials == null) && (this.signature == null))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SamlAssertionMissingSigningCredentials)));

            XmlDictionaryWriter dictionaryWriter = XmlDictionaryWriter.CreateDictionaryWriter(writer);

            if (this.signingCredentials != null)
            {
                using (HashAlgorithm hash = CryptoHelper.CreateHashAlgorithm(this.signingCredentials.DigestAlgorithm))
                {
                    this.hashStream = new HashStream(hash);
                    this.keyInfoSerializer = keyInfoSerializer;
                    this.dictionaryManager = samlSerializer.DictionaryManager;
                    SamlDelegatingWriter delegatingWriter = new SamlDelegatingWriter(dictionaryWriter, this.hashStream, this, samlSerializer.DictionaryManager.ParentDictionary);
                    this.WriteXml(delegatingWriter, samlSerializer, keyInfoSerializer);
                }
            }
            else
            {
                this.tokenStream.SetElementExclusion(null, null);
                this.tokenStream.WriteTo(dictionaryWriter, samlSerializer.DictionaryManager);
            }
        }
 protected virtual void ComputeHash(HashStream hashStream)
 {
     if (this.sendSide)
     {
         XmlDictionaryWriter writer = this.ResourcePool.TakeUtf8Writer();
         writer.StartCanonicalization(hashStream, false, null);
         this.WriteTo(writer, this.dictionaryManager);
         writer.EndCanonicalization();
     }
     else if (this.canonicalStream != null)
     {
         this.canonicalStream.WriteTo(hashStream);
     }
     else
     {
         if (this.readerProvider == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("InclusiveNamespacePrefixRequiresSignatureReader")));
         }
         XmlDictionaryReader reader = this.readerProvider.GetReader(this.signatureReaderProviderCallbackContext);
         if (!reader.CanCanonicalize)
         {
             MemoryStream stream = new MemoryStream();
             XmlDictionaryWriter writer2 = XmlDictionaryWriter.CreateBinaryWriter(stream, this.DictionaryManager.ParentDictionary);
             string[] inclusivePrefixes = this.GetInclusivePrefixes();
             if (inclusivePrefixes != null)
             {
                 writer2.WriteStartElement("a");
                 for (int i = 0; i < inclusivePrefixes.Length; i++)
                 {
                     string namespaceForInclusivePrefix = this.GetNamespaceForInclusivePrefix(inclusivePrefixes[i]);
                     if (namespaceForInclusivePrefix != null)
                     {
                         writer2.WriteXmlnsAttribute(inclusivePrefixes[i], namespaceForInclusivePrefix);
                     }
                 }
             }
             reader.MoveToContent();
             writer2.WriteNode(reader, false);
             if (inclusivePrefixes != null)
             {
                 writer2.WriteEndElement();
             }
             writer2.Flush();
             byte[] buffer = stream.ToArray();
             int length = (int) stream.Length;
             writer2.Close();
             reader.Close();
             reader = XmlDictionaryReader.CreateBinaryReader(buffer, 0, length, this.DictionaryManager.ParentDictionary, XmlDictionaryReaderQuotas.Max);
             if (inclusivePrefixes != null)
             {
                 reader.ReadStartElement("a");
             }
         }
         reader.ReadStartElement(this.dictionaryManager.XmlSignatureDictionary.Signature, this.dictionaryManager.XmlSignatureDictionary.Namespace);
         reader.MoveToStartElement(this.dictionaryManager.XmlSignatureDictionary.SignedInfo, this.dictionaryManager.XmlSignatureDictionary.Namespace);
         reader.StartCanonicalization(hashStream, false, this.GetInclusivePrefixes());
         reader.Skip();
         reader.EndCanonicalization();
         reader.Close();
     }
 }
        /// <summary>
        /// Initializes an instance of <see cref="EnvelopedSignatureWriter"/>. The returned writer can be directly used
        /// to write the envelope. The signature will be automatically generated when 
        /// the envelope is completed.
        /// </summary>
        /// <param name="innerWriter">Writer to wrap/</param>
        /// <param name="signingCredentials">SigningCredentials to be used to generate the signature.</param>
        /// <param name="referenceId">The reference Id of the envelope.</param>
        /// <param name="securityTokenSerializer">SecurityTokenSerializer to serialize the signature KeyInfo.</param>
        /// <exception cref="ArgumentNullException">One of he input parameter is null.</exception>
        /// <exception cref="ArgumentException">The string 'referenceId' is either null or empty.</exception>
        public EnvelopedSignatureWriter(XmlWriter innerWriter, SigningCredentials signingCredentials, string referenceId, SecurityTokenSerializer securityTokenSerializer)
        {
            if (innerWriter == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("innerWriter");
            }

            if (signingCredentials == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("signingCredentials");
            }

            if (string.IsNullOrEmpty(referenceId))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.ID0006), "referenceId"));
            }

            if (securityTokenSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenSerializer");
            }

            // Remember the user's writer here. We need to finally write out the signed XML
            // into this writer.
            _dictionaryManager = new DictionaryManager();
            _innerWriter = innerWriter;
            _signingCreds = signingCredentials;
            _referenceId = referenceId;
            _tokenSerializer = securityTokenSerializer;

            _signatureFragment = new MemoryStream();
            _endFragment = new MemoryStream();
            _writerStream = new MemoryStream();

            XmlDictionaryWriter effectiveWriter = XmlDictionaryWriter.CreateTextWriter(_writerStream, Encoding.UTF8, false);

            // Initialize the base writer to the newly created writer. The user should write the XML
            // to this.
            base.InitializeInnerWriter(effectiveWriter);
            _hashAlgorithm = CryptoHelper.CreateHashAlgorithm(_signingCreds.DigestAlgorithm);
            _hashStream = new HashStream(_hashAlgorithm);
            base.InnerWriter.StartCanonicalization(_hashStream, false, null);

            //
            // Add tracing for the un-canonicalized bytes
            //
            if (DiagnosticUtility.ShouldTraceVerbose)
            {
                _preCanonicalTracingStream = new MemoryStream();
                base.InitializeTracingWriter(new XmlTextWriter(_preCanonicalTracingStream, Encoding.UTF8));
            }
        }
Пример #15
0
 protected override void ComputeHash(HashStream hashStream)
 {
     if (SendSide)
     {
         using (XmlDictionaryWriter utf8Writer = XmlDictionaryWriter.CreateTextWriter(Stream.Null, Encoding.UTF8, false))
         {
             utf8Writer.StartCanonicalization(hashStream, false, null);
             WriteTo(utf8Writer, DictionaryManager);
             utf8Writer.EndCanonicalization();
         }
     }
     else if (CanonicalStream != null)
     {
         CanonicalStream.WriteTo(hashStream);
     }
     else
     {
         _bufferedStream.Position = 0;
         // We are creating a XmlDictionaryReader with a hard-coded Max XmlDictionaryReaderQuotas. This is a reader that we
         // are creating over an already buffered content. The content was initially read off user provided XmlDictionaryReader
         // with the correct quotas and hence we know the data is valid.
         // Note: signedinfoReader will close _bufferedStream on Dispose.
         using (XmlDictionaryReader signedinfoReader = XmlDictionaryReader.CreateTextReader(_bufferedStream, XmlDictionaryReaderQuotas.Max))
         {
             signedinfoReader.MoveToContent();
             using (XmlDictionaryWriter bufferingWriter = XmlDictionaryWriter.CreateTextWriter(Stream.Null, Encoding.UTF8, false))
             {
                 bufferingWriter.WriteStartElement("a", _defaultNamespace);
                 string[] inclusivePrefix = GetInclusivePrefixes();
                 for (int i = 0; i < inclusivePrefix.Length; ++i)
                 {
                     string ns = GetNamespaceForInclusivePrefix(inclusivePrefix[i]);
                     if (ns != null)
                     {
                         bufferingWriter.WriteXmlnsAttribute(inclusivePrefix[i], ns);
                     }
                 }
                 bufferingWriter.StartCanonicalization(hashStream, false, inclusivePrefix);
                 bufferingWriter.WriteNode(signedinfoReader, false);
                 bufferingWriter.EndCanonicalization();
                 bufferingWriter.WriteEndElement();
             }
         }
     }
 }
Пример #16
0
        protected virtual void ComputeHash(HashStream hashStream)
        {
            if (this.sendSide)
            {
                XmlDictionaryWriter utf8Writer = this.ResourcePool.TakeUtf8Writer();
                utf8Writer.StartCanonicalization(hashStream, false, null);
                WriteTo(utf8Writer, this.dictionaryManager);
                utf8Writer.EndCanonicalization();
            }
            else if (this.canonicalStream != null)
            {
                this.canonicalStream.WriteTo(hashStream);
            }
            else
            {
                if (this.readerProvider == null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.InclusiveNamespacePrefixRequiresSignatureReader)));

                XmlDictionaryReader signatureReader = this.readerProvider.GetReader(this.signatureReaderProviderCallbackContext);

                DiagnosticUtility.DebugAssert(signatureReader != null, "Require a Signature reader to validate signature.");

                if (!signatureReader.CanCanonicalize)
                {
                    MemoryStream stream = new MemoryStream();
                    XmlDictionaryWriter bufferingWriter = XmlDictionaryWriter.CreateBinaryWriter(stream, this.DictionaryManager.ParentDictionary);
                    string[] inclusivePrefix = GetInclusivePrefixes();
                    if (inclusivePrefix != null)
                    {
                        bufferingWriter.WriteStartElement("a");
                        for (int i = 0; i < inclusivePrefix.Length; ++i)
                        {
                            string ns = GetNamespaceForInclusivePrefix(inclusivePrefix[i]);
                            if (ns != null)
                            {
                                bufferingWriter.WriteXmlnsAttribute(inclusivePrefix[i], ns);
                            }
                        }
                    }
                    signatureReader.MoveToContent();
                    bufferingWriter.WriteNode(signatureReader, false);
                    if (inclusivePrefix != null)
                        bufferingWriter.WriteEndElement();
                    bufferingWriter.Flush();
                    byte[] buffer = stream.ToArray();
                    int bufferLength = (int)stream.Length;
                    bufferingWriter.Close();

                    signatureReader.Close();

                    // Create a reader around the buffering Stream.
                    signatureReader = XmlDictionaryReader.CreateBinaryReader(buffer, 0, bufferLength, this.DictionaryManager.ParentDictionary, XmlDictionaryReaderQuotas.Max);
                    if (inclusivePrefix != null)
                        signatureReader.ReadStartElement("a");
                }
                signatureReader.ReadStartElement(dictionaryManager.XmlSignatureDictionary.Signature, dictionaryManager.XmlSignatureDictionary.Namespace);
                signatureReader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.SignedInfo, dictionaryManager.XmlSignatureDictionary.Namespace);
                signatureReader.StartCanonicalization(hashStream, false, GetInclusivePrefixes());
                signatureReader.Skip();
                signatureReader.EndCanonicalization();
                signatureReader.Close();
            }
        }
Пример #17
0
        private void ProcessReaderInput(XmlReader reader, SignatureResourcePool resourcePool, HashStream hashStream)
        {
            reader.MoveToContent();
            XmlDictionaryReader reader2 = reader as XmlDictionaryReader;

            if ((reader2 != null) && reader2.CanCanonicalize)
            {
                reader2.StartCanonicalization(hashStream, this.IncludeComments, this.GetInclusivePrefixes());
                reader2.Skip();
                reader2.EndCanonicalization();
            }
            else
            {
                CanonicalizationDriver configuredDriver = this.GetConfiguredDriver(resourcePool);
                configuredDriver.SetInput(reader);
                configuredDriver.WriteTo(hashStream);
            }
        }
        private void ComputeSignature()
        {
            PreDigestedSignedInfo signedInfo = new PreDigestedSignedInfo(_dictionaryManager);
            signedInfo.AddEnvelopedSignatureTransform = true;
            signedInfo.CanonicalizationMethod = XD.ExclusiveC14NDictionary.Namespace.Value;
            signedInfo.SignatureMethod = _signingCreds.SignatureAlgorithm;
            signedInfo.DigestMethod = _signingCreds.DigestAlgorithm;
            signedInfo.AddReference(_referenceId, _hashStream.FlushHashAndGetValue(_preCanonicalTracingStream));

            SignedXml signedXml = new SignedXml(signedInfo, _dictionaryManager, _tokenSerializer);
            signedXml.ComputeSignature(_signingCreds.SigningKey);
            signedXml.Signature.KeyIdentifier = _signingCreds.SigningKeyIdentifier;
            signedXml.WriteTo(base.InnerWriter);
            ((IDisposable)_hashStream).Dispose();
            _hashStream = null;
        }
Пример #19
0
 protected virtual void ComputeHash(HashStream hashStream)
 {
     if (this.sendSide)
     {
         XmlDictionaryWriter writer = this.ResourcePool.TakeUtf8Writer();
         writer.StartCanonicalization(hashStream, false, null);
         this.WriteTo(writer, this.dictionaryManager);
         writer.EndCanonicalization();
     }
     else if (this.canonicalStream != null)
     {
         this.canonicalStream.WriteTo(hashStream);
     }
     else
     {
         if (this.readerProvider == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("InclusiveNamespacePrefixRequiresSignatureReader")));
         }
         XmlDictionaryReader reader = this.readerProvider.GetReader(this.signatureReaderProviderCallbackContext);
         if (!reader.CanCanonicalize)
         {
             MemoryStream        stream            = new MemoryStream();
             XmlDictionaryWriter writer2           = XmlDictionaryWriter.CreateBinaryWriter(stream, this.DictionaryManager.ParentDictionary);
             string[]            inclusivePrefixes = this.GetInclusivePrefixes();
             if (inclusivePrefixes != null)
             {
                 writer2.WriteStartElement("a");
                 for (int i = 0; i < inclusivePrefixes.Length; i++)
                 {
                     string namespaceForInclusivePrefix = this.GetNamespaceForInclusivePrefix(inclusivePrefixes[i]);
                     if (namespaceForInclusivePrefix != null)
                     {
                         writer2.WriteXmlnsAttribute(inclusivePrefixes[i], namespaceForInclusivePrefix);
                     }
                 }
             }
             reader.MoveToContent();
             writer2.WriteNode(reader, false);
             if (inclusivePrefixes != null)
             {
                 writer2.WriteEndElement();
             }
             writer2.Flush();
             byte[] buffer = stream.ToArray();
             int    length = (int)stream.Length;
             writer2.Close();
             reader.Close();
             reader = XmlDictionaryReader.CreateBinaryReader(buffer, 0, length, this.DictionaryManager.ParentDictionary, XmlDictionaryReaderQuotas.Max);
             if (inclusivePrefixes != null)
             {
                 reader.ReadStartElement("a");
             }
         }
         reader.ReadStartElement(this.dictionaryManager.XmlSignatureDictionary.Signature, this.dictionaryManager.XmlSignatureDictionary.Namespace);
         reader.MoveToStartElement(this.dictionaryManager.XmlSignatureDictionary.SignedInfo, this.dictionaryManager.XmlSignatureDictionary.Namespace);
         reader.StartCanonicalization(hashStream, false, this.GetInclusivePrefixes());
         reader.Skip();
         reader.EndCanonicalization();
         reader.Close();
     }
 }
 protected override void StartPrimarySignatureCore(SecurityToken token, SecurityKeyIdentifier keyIdentifier, MessagePartSpecification signatureParts, bool generateTargettableSignature)
 {
     string str3;
     XmlDictionaryString str4;
     SecurityAlgorithmSuite algorithmSuite = base.AlgorithmSuite;
     string defaultCanonicalizationAlgorithm = algorithmSuite.DefaultCanonicalizationAlgorithm;
     XmlDictionaryString defaultCanonicalizationAlgorithmDictionaryString = algorithmSuite.DefaultCanonicalizationAlgorithmDictionaryString;
     if (defaultCanonicalizationAlgorithm != "http://www.w3.org/2001/10/xml-exc-c14n#")
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("UnsupportedCanonicalizationAlgorithm", new object[] { algorithmSuite.DefaultCanonicalizationAlgorithm })));
     }
     algorithmSuite.GetSignatureAlgorithmAndKey(token, out str3, out this.signatureKey, out str4);
     string defaultDigestAlgorithm = algorithmSuite.DefaultDigestAlgorithm;
     XmlDictionaryString defaultDigestAlgorithmDictionaryString = algorithmSuite.DefaultDigestAlgorithmDictionaryString;
     this.signedInfo = new PreDigestedSignedInfo(ServiceModelDictionaryManager.Instance, defaultCanonicalizationAlgorithm, defaultCanonicalizationAlgorithmDictionaryString, defaultDigestAlgorithm, defaultDigestAlgorithmDictionaryString, str3, str4);
     this.signedXml = new SignedXml(this.signedInfo, ServiceModelDictionaryManager.Instance, base.StandardsManager.SecurityTokenSerializer);
     if (keyIdentifier != null)
     {
         this.signedXml.Signature.KeyIdentifier = keyIdentifier;
     }
     if (generateTargettableSignature)
     {
         this.signedXml.Id = base.GenerateId();
     }
     this.effectiveSignatureParts = signatureParts;
     this.hashStream = this.signedInfo.ResourcePool.TakeHashStream(defaultDigestAlgorithm);
 }
 void ProcessReaderInput(XmlReader reader, SignatureResourcePool resourcePool, HashStream hashStream)
 {
     reader.MoveToContent();
     XmlDictionaryReader dictionaryReader = reader as XmlDictionaryReader;
     if (dictionaryReader != null && dictionaryReader.CanCanonicalize)
     {
         dictionaryReader.StartCanonicalization(hashStream, this.IncludeComments, GetInclusivePrefixes());
         dictionaryReader.Skip();
         dictionaryReader.EndCanonicalization();
     }
     else
     {
         CanonicalizationDriver driver = GetConfiguredDriver(resourcePool);
         driver.SetInput(reader);
         driver.WriteTo(hashStream);
     }
 }
 private HashStream TakeHashStream()
 {
     HashStream hashStream = null;
     if (this.hashStream == null)
     {
         this.hashStream = hashStream = new HashStream(System.ServiceModel.Security.CryptoHelper.CreateHashAlgorithm(base.AlgorithmSuite.DefaultDigestAlgorithm));
         return hashStream;
     }
     hashStream = this.hashStream;
     hashStream.Reset();
     return hashStream;
 }
        /// <summary>
        /// Releases the unmanaged resources used by the System.IdentityModel.Protocols.XmlSignature.EnvelopedSignatureWriter and optionally
        /// releases the managed resources.
        /// </summary>
        /// <param name="disposing">
        /// True to release both managed and unmanaged resources; false to release only unmanaged resources.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (_disposed)
            {
                return;
            }

            if (disposing)
            {
                //
                // Free all of our managed resources
                //
                if (_hashStream != null)
                {
                    _hashStream.Dispose();
                    _hashStream = null;
                }

                if (_hashAlgorithm != null)
                {
                    ((IDisposable)_hashAlgorithm).Dispose();
                    _hashAlgorithm = null;
                }

                if (_signatureFragment != null)
                {
                    _signatureFragment.Dispose();
                    _signatureFragment = null;
                }

                if (_endFragment != null)
                {
                    _endFragment.Dispose();
                    _endFragment = null;
                }

                if (_writerStream != null)
                {
                    _writerStream.Dispose();
                    _writerStream = null;
                }

                if (_preCanonicalTracingStream != null)
                {
                    _preCanonicalTracingStream.Dispose();
                    _preCanonicalTracingStream = null;
                }
            }

            // Free native resources, if any.

            _disposed = true;
        }