WSSecurityJan2004.cs source code in C# .NET

Source code for the .NET framework in C#

                        

Code:

/ WCF / WCF / 3.5.30729.1 / untmp / Orcas / SP / ndp / cdf / src / WCF / ServiceModel / System / ServiceModel / Security / WSSecurityJan2004.cs / 1 / WSSecurityJan2004.cs

                            //------------------------------------------------------------ 
// Copyright (c) Microsoft Corporation.  All rights reserved.
//-----------------------------------------------------------

namespace System.ServiceModel.Security 
{
    using System; 
    using System.ServiceModel; 
    using System.ServiceModel.Description;
    using System.Collections; 
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO; 
    using System.Text;
    using System.Threading; 
    using System.Xml; 
    using System.IdentityModel.Claims;
    using System.IdentityModel.Policy; 
    using System.IdentityModel.Selectors;
    using System.IdentityModel.Tokens;
    using System.Security.Cryptography;
    using System.Security.Cryptography.X509Certificates; 
    using System.ServiceModel.Security.Tokens;
    using HexBinary = System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary; 
    using System.ServiceModel.Channels; 
    using System.ServiceModel.Security;
    using System.Runtime.Serialization; 

    using KeyIdentifierEntry = WSSecurityTokenSerializer.KeyIdentifierEntry;
    using KeyIdentifierClauseEntry = WSSecurityTokenSerializer.KeyIdentifierClauseEntry;
    using TokenEntry = WSSecurityTokenSerializer.TokenEntry; 
    using StrEntry = WSSecurityTokenSerializer.StrEntry;
 
    class WSSecurityJan2004 : WSSecurityTokenSerializer.SerializerEntries 
    {
        WSSecurityTokenSerializer tokenSerializer; 
        SamlSerializer samlSerializer;

        public WSSecurityJan2004(WSSecurityTokenSerializer tokenSerializer, SamlSerializer samlSerializer)
        { 
            this.tokenSerializer = tokenSerializer;
            this.samlSerializer = samlSerializer; 
        } 

        public WSSecurityTokenSerializer WSSecurityTokenSerializer 
        {
            get { return this.tokenSerializer; }
        }
 
        public SamlSerializer SamlSerializer
        { 
            get { return this.samlSerializer; } 
        }
 
        public override void PopulateKeyIdentifierClauseEntries(IList clauseEntries)
        {
            List strEntries = new List();
            this.tokenSerializer.PopulateStrEntries(strEntries); 
            SecurityTokenReferenceJan2004ClauseEntry strClause = new SecurityTokenReferenceJan2004ClauseEntry(this.tokenSerializer, strEntries);
            clauseEntries.Add(strClause); 
        } 

        protected void PopulateJan2004StrEntries(IList strEntries) 
        {
            strEntries.Add(new LocalReferenceStrEntry(this.tokenSerializer));
            strEntries.Add(new KerberosHashStrEntry(this.tokenSerializer));
            strEntries.Add(new X509SkiStrEntry(this.tokenSerializer)); 
            strEntries.Add(new X509IssuerSerialStrEntry());
            strEntries.Add(new RelDirectStrEntry()); 
        } 

 
        public override void PopulateStrEntries(IList strEntries)
        {
            PopulateJan2004StrEntries(strEntries);
            strEntries.Add(new SamlJan2004KeyIdentifierStrEntry()); 
        }
 
        protected void PopulateJan2004TokenEntries(IList tokenEntryList) 
        {
            tokenEntryList.Add(new GenericXmlTokenEntry()); 
            tokenEntryList.Add(new UserNamePasswordTokenEntry(this.tokenSerializer));
            tokenEntryList.Add(new KerberosTokenEntry(this.tokenSerializer));
            tokenEntryList.Add(new X509TokenEntry(this.tokenSerializer));
        } 

        public override void PopulateTokenEntries(IList tokenEntryList) 
        { 
            PopulateJan2004TokenEntries(tokenEntryList);
            tokenEntryList.Add(new SamlTokenEntry(this.tokenSerializer, this.samlSerializer)); 
            tokenEntryList.Add(new WrappedKeyTokenEntry(this.tokenSerializer));
        }

        internal abstract class BinaryTokenEntry : TokenEntry 
        {
            internal static readonly XmlDictionaryString ElementName = XD.SecurityJan2004Dictionary.BinarySecurityToken; 
            internal static readonly XmlDictionaryString EncodingTypeAttribute = XD.SecurityJan2004Dictionary.EncodingType; 
            internal const string EncodingTypeAttributeString = SecurityJan2004Strings.EncodingType;
            internal const string EncodingTypeValueBase64Binary = SecurityJan2004Strings.EncodingTypeValueBase64Binary; 
            internal const string EncodingTypeValueHexBinary = SecurityJan2004Strings.EncodingTypeValueHexBinary;
            internal static readonly XmlDictionaryString ValueTypeAttribute = XD.SecurityJan2004Dictionary.ValueType;

            WSSecurityTokenSerializer tokenSerializer; 
            string[] valueTypeUris = null;
 
            protected BinaryTokenEntry(WSSecurityTokenSerializer tokenSerializer, string valueTypeUri) 
            {
                this.tokenSerializer = tokenSerializer; 
                this.valueTypeUris = new string[1];
                this.valueTypeUris[0] = valueTypeUri;
            }
 
            protected BinaryTokenEntry(WSSecurityTokenSerializer tokenSerializer, string[] valueTypeUris)
            { 
                if (valueTypeUris == null) 
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("valueTypeUris");
 
                this.tokenSerializer = tokenSerializer;
                this.valueTypeUris = new string[valueTypeUris.GetLength(0)];
                for (int i = 0; i < this.valueTypeUris.GetLength(0); ++i)
                    this.valueTypeUris[i] = valueTypeUris[i]; 
            }
 
            protected override XmlDictionaryString LocalName { get { return ElementName; } } 
            protected override XmlDictionaryString NamespaceUri { get { return XD.SecurityJan2004Dictionary.Namespace; } }
            public override string TokenTypeUri { get {return this.valueTypeUris[0]; } } 
            protected override string ValueTypeUri { get { return this.valueTypeUris[0]; } }
            public override bool SupportsTokenTypeUri(string tokenTypeUri)
            {
                for (int i = 0; i < this.valueTypeUris.GetLength(0); ++i) 
                {
                    if (this.valueTypeUris[i] == tokenTypeUri) 
                        return true; 
                }
 
                return false;
            }

            public abstract SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromBinaryCore(byte[] rawData); 

            public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml, 
                SecurityTokenReferenceStyle tokenReferenceStyle) 
            {
                TokenReferenceStyleHelper.Validate(tokenReferenceStyle); 

                switch (tokenReferenceStyle)
                {
                    case SecurityTokenReferenceStyle.Internal: 
                        return CreateDirectReference(issuedTokenXml, UtilityStrings.IdAttribute, UtilityStrings.Namespace, this.TokenType);
                    case SecurityTokenReferenceStyle.External: 
                        string encoding = issuedTokenXml.GetAttribute(EncodingTypeAttributeString, null); 
                        string encodedData = issuedTokenXml.InnerText;
 
                        byte[] binaryData;
                        if (encoding == null || encoding == EncodingTypeValueBase64Binary)
                        {
                            binaryData = Convert.FromBase64String(encodedData); 
                        }
                        else if (encoding == EncodingTypeValueHexBinary) 
                        { 
                            binaryData = HexBinary.Parse(encodedData).Value;
                        } 
                        else
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.UnknownEncodingInBinarySecurityToken)));
                        } 

                        return CreateKeyIdentifierClauseFromBinaryCore(binaryData); 
                    default: 
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("tokenReferenceStyle"));
                } 
            }

            public abstract SecurityToken ReadBinaryCore(string id, byte[] rawData);
 
            public override SecurityToken  ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver)
            { 
                string wsuId = reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace); 
                string encoding = reader.GetAttribute(EncodingTypeAttribute, null);
 
                byte[] binaryData;
                if (encoding == null || encoding == EncodingTypeValueBase64Binary)
                {
                    binaryData = reader.ReadElementContentAsBase64(); 
                }
                else if (encoding == EncodingTypeValueHexBinary) 
                { 
                    binaryData = HexBinary.Parse(reader.ReadElementContentAsString()).Value;
                } 
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.UnknownEncodingInBinarySecurityToken)));
                } 

                return ReadBinaryCore(wsuId, binaryData); 
            } 

            public abstract void WriteBinaryCore(SecurityToken token, out string id, out byte[] rawData); 

            public override void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token)
            {
                string id; 
                byte[] rawData;
 
                WriteBinaryCore(token, out id, out rawData); 

                if (rawData == null) 
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rawData");
                }
 
                writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, ElementName, XD.SecurityJan2004Dictionary.Namespace);
                if (id != null) 
                { 
                    writer.WriteAttributeString(XD.UtilityDictionary.Prefix.Value, XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace, id);
                } 
                if (valueTypeUris != null)
                {
                    writer.WriteAttributeString(ValueTypeAttribute, null, this.valueTypeUris[0]);
                } 
                if (this.tokenSerializer.EmitBspRequiredAttributes)
                { 
                    writer.WriteAttributeString(EncodingTypeAttribute, null, EncodingTypeValueBase64Binary); 
                }
                writer.WriteBase64(rawData, 0, rawData.Length); 
                writer.WriteEndElement(); // BinarySecurityToken
            }
        }
 
        class GenericXmlTokenEntry : TokenEntry
        { 
            protected override XmlDictionaryString LocalName { get { return null; } } 
            protected override XmlDictionaryString NamespaceUri { get { return null; } }
            protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(GenericXmlSecurityToken) }; } 
            public override string TokenTypeUri { get { return null; } }
            protected override string ValueTypeUri { get { return null; } }

            public GenericXmlTokenEntry() 
            {
            } 
 

            public override bool CanReadTokenCore(XmlElement element) 
            {
                return false;
            }
 
            public override bool CanReadTokenCore(XmlDictionaryReader reader)
            { 
                return false; 
            }
 
            public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml,
                SecurityTokenReferenceStyle tokenReferenceStyle)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); 
            }
 
            public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver) 
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); 
            }

            public override void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token)
            { 
                BufferedGenericXmlSecurityToken bufferedXmlToken = token as BufferedGenericXmlSecurityToken;
                if (bufferedXmlToken != null && bufferedXmlToken.TokenXmlBuffer != null) 
                { 
                    using (XmlDictionaryReader reader = bufferedXmlToken.TokenXmlBuffer.GetReader(0))
                    { 
                        writer.WriteNode(reader, false);
                    }
                }
                else 
                {
                    GenericXmlSecurityToken xmlToken = (GenericXmlSecurityToken)token; 
                    xmlToken.TokenXml.WriteTo(writer); 
                }
            } 
        }

        class KerberosTokenEntry : BinaryTokenEntry
        { 
            public KerberosTokenEntry(WSSecurityTokenSerializer tokenSerializer)
                : base(tokenSerializer, new string[] { SecurityJan2004Strings.KerberosTokenTypeGSS, SecurityJan2004Strings.KerberosTokenType1510 }) 
            { 
            }
 
            protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(KerberosReceiverSecurityToken), typeof(KerberosRequestorSecurityToken) }; }

            public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromBinaryCore(byte[] rawData)
            { 
                byte[] tokenHash;
                using (HashAlgorithm hasher = CryptoHelper.NewSha1HashAlgorithm()) 
                { 
                    tokenHash = hasher.ComputeHash(rawData, 0, rawData.Length);
                } 
                return new KerberosTicketHashKeyIdentifierClause(tokenHash);
            }

            public override SecurityToken ReadBinaryCore(string id, byte[] rawData) 
            {
                return new KerberosReceiverSecurityToken(rawData, id, false); 
            } 

            public override void WriteBinaryCore(SecurityToken token, out string id, out byte[] rawData) 
            {
                KerberosRequestorSecurityToken kerbToken = (KerberosRequestorSecurityToken)token;
                id = token.Id;
                rawData = kerbToken.GetRequest(); 
            }
        } 
 
        protected class SamlTokenEntry : TokenEntry
        { 
            const string samlAssertionId = "AssertionID";
            SamlSerializer samlSerializer;
            SecurityTokenSerializer tokenSerializer;
 
            public SamlTokenEntry(SecurityTokenSerializer tokenSerializer, SamlSerializer samlSerializer)
            { 
                this.tokenSerializer = tokenSerializer; 
                if (samlSerializer != null)
                { 
                    this.samlSerializer = samlSerializer;
                }
                else
                { 
                    this.samlSerializer = new SamlSerializer();
                } 
                this.samlSerializer.PopulateDictionary(BinaryMessageEncoderFactory.XmlDictionary); 
            }
 
            protected override XmlDictionaryString LocalName { get { return XD.SecurityJan2004Dictionary.SamlAssertion; } }
            protected override XmlDictionaryString NamespaceUri { get { return XD.SecurityJan2004Dictionary.SamlUri; } }
            protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(SamlSecurityToken) }; }
            public override string TokenTypeUri { get { return null; } } 
            protected override string ValueTypeUri { get { return null; } }
 
            public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml, 
                SecurityTokenReferenceStyle tokenReferenceStyle)
            { 
                TokenReferenceStyleHelper.Validate(tokenReferenceStyle);

                switch (tokenReferenceStyle)
                { 
                    // SAML uses same reference for internal and external
                    case SecurityTokenReferenceStyle.Internal: 
                    case SecurityTokenReferenceStyle.External: 
                        string assertionId = issuedTokenXml.GetAttribute(samlAssertionId);
                        return new SamlAssertionKeyIdentifierClause(assertionId); 
                    default:
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("tokenReferenceStyle"));
                }
            } 

            public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver) 
            { 
                SamlSecurityToken samlToken = this.samlSerializer.ReadToken(reader, this.tokenSerializer, tokenResolver);
                return samlToken; 
            }

            public override void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token)
            { 
                SamlSecurityToken samlToken = token as SamlSecurityToken;
                this.samlSerializer.WriteToken(samlToken, writer, this.tokenSerializer); 
            } 
        }
 
        class UserNamePasswordTokenEntry : TokenEntry
        {
            WSSecurityTokenSerializer tokenSerializer;
 
            public UserNamePasswordTokenEntry(WSSecurityTokenSerializer tokenSerializer)
            { 
                this.tokenSerializer = tokenSerializer; 
            }
 
            protected override XmlDictionaryString LocalName { get { return XD.SecurityJan2004Dictionary.UserNameTokenElement; } }
            protected override XmlDictionaryString NamespaceUri { get { return XD.SecurityJan2004Dictionary.Namespace; } }
            protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(UserNameSecurityToken) }; }
            public override string TokenTypeUri { get { return SecurityJan2004Strings.UPTokenType; } } 
            protected override string ValueTypeUri { get { return null; } }
 
            public override IAsyncResult BeginReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver, AsyncCallback callback, object state) 
            {
                string id; 
                string userName;
                string password;

                ParseToken(reader, out id, out userName, out password); 

                SecurityToken token = new UserNameSecurityToken(userName, password, id); 
                return new TypedCompletedAsyncResult(token, callback, state); 
            }
 
            public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml,
                SecurityTokenReferenceStyle tokenReferenceStyle)
            {
                TokenReferenceStyleHelper.Validate(tokenReferenceStyle); 

                switch (tokenReferenceStyle) 
                { 
                    case SecurityTokenReferenceStyle.Internal:
                        return CreateDirectReference(issuedTokenXml, UtilityStrings.IdAttribute, UtilityStrings.Namespace, typeof(UserNameSecurityToken)); 
                    case SecurityTokenReferenceStyle.External:
                        // UP tokens aren't referred to externally
                        return null;
                    default: 
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("tokenReferenceStyle"));
                } 
            } 

            public override SecurityToken EndReadTokenCore(IAsyncResult result) 
            {
                return TypedCompletedAsyncResult.End(result);
            }
 
            public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver)
            { 
                string id; 
                string userName;
                string password; 

                ParseToken(reader, out id, out userName, out password);

                if (id == null) 
                    id = SecurityUniqueId.Create().Value;
 
                return new UserNameSecurityToken(userName, password, id); 
            }
 
            public override void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token)
            {
                UserNameSecurityToken upToken = (UserNameSecurityToken)token;
                WriteUserNamePassword(writer, upToken.Id, upToken.UserName, upToken.Password); 
            }
 
            void WriteUserNamePassword(XmlDictionaryWriter writer, string id, string userName, string password) 
            {
                writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.UserNameTokenElement, 
                    XD.SecurityJan2004Dictionary.Namespace); // ...
                if (password != null) 
                { 
                    writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.PasswordElement,
                        XD.SecurityJan2004Dictionary.Namespace); 
                    if (this.tokenSerializer.EmitBspRequiredAttributes)
                    {
                        writer.WriteAttributeString(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.TypeAttribute, null, SecurityJan2004Strings.UPTokenPasswordTextValue);
                    } 
                    writer.WriteString(password); // ...
                    writer.WriteEndElement(); 
                } 
                writer.WriteEndElement(); // 
            } 

            static string ParsePassword(XmlDictionaryReader reader)
            {
                string type = reader.GetAttribute(XD.SecurityJan2004Dictionary.TypeAttribute, null); 
                if (type != null && type.Length > 0 &&  type != SecurityJan2004Strings.UPTokenPasswordTextValue)
                { 
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.UnsupportedPasswordType, type))); 
                }
 
                return reader.ReadElementString();
            }

            static void ParseToken(XmlDictionaryReader reader, out string id, out string userName, out string password) 
            {
                id = null; 
                userName = null; 
                password = null;
 
                reader.MoveToContent();
                id = reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace);

                reader.ReadStartElement(XD.SecurityJan2004Dictionary.UserNameTokenElement, XD.SecurityJan2004Dictionary.Namespace); 
                while (reader.IsStartElement())
                { 
                    if (reader.IsStartElement(XD.SecurityJan2004Dictionary.UserNameElement, XD.SecurityJan2004Dictionary.Namespace)) 
                    {
                        userName = reader.ReadElementString(); 
                    }
                    else if (reader.IsStartElement(XD.SecurityJan2004Dictionary.PasswordElement, XD.SecurityJan2004Dictionary.Namespace))
                    {
                        password = ParsePassword(reader); 
                    }
                    else if (reader.IsStartElement(XD.SecurityJan2004Dictionary.NonceElement, XD.SecurityJan2004Dictionary.Namespace)) 
                    { 
                        // Nonce can be safely ignored
                        reader.Skip(); 
                    }
                    else if (reader.IsStartElement(XD.UtilityDictionary.CreatedElement, XD.UtilityDictionary.Namespace))
                    {
                        // wsu:Created can be safely ignored 
                        reader.Skip();
                    } 
                    else 
                    {
                        XmlHelper.OnUnexpectedChildNodeError(SecurityJan2004Strings.UserNameTokenElement, reader); 
                    }
                }
                reader.ReadEndElement();
 
                if (userName == null)
                    XmlHelper.OnRequiredElementMissing(SecurityJan2004Strings.UserNameElement, SecurityJan2004Strings.Namespace); 
            } 
        }
 
        protected class WrappedKeyTokenEntry : TokenEntry
        {
            WSSecurityTokenSerializer tokenSerializer;
 
            public WrappedKeyTokenEntry(WSSecurityTokenSerializer tokenSerializer)
            { 
                this.tokenSerializer = tokenSerializer; 
            }
 
            protected override XmlDictionaryString LocalName { get { return EncryptedKey.ElementName; } }
            protected override XmlDictionaryString NamespaceUri { get { return XD.XmlEncryptionDictionary.Namespace; } }
            protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(WrappedKeySecurityToken) }; }
            public override string TokenTypeUri { get { return null; } } 
            protected override string ValueTypeUri { get { return null; } }
 
            public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml, 
                SecurityTokenReferenceStyle tokenReferenceStyle)
            { 

                TokenReferenceStyleHelper.Validate(tokenReferenceStyle);

                switch (tokenReferenceStyle) 
                {
                    case SecurityTokenReferenceStyle.Internal: 
                        return CreateDirectReference(issuedTokenXml, XmlEncryptionStrings.Id, null, null); 
                    case SecurityTokenReferenceStyle.External:
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.CantInferReferenceForToken, EncryptedKey.ElementName.Value))); 
                    default:
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("tokenReferenceStyle"));
                }
            } 

            public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver) 
            { 
                EncryptedKey encryptedKey = new EncryptedKey();
                encryptedKey.SecurityTokenSerializer = this.tokenSerializer; 
                encryptedKey.ReadFrom(reader);
                SecurityKeyIdentifier unwrappingTokenIdentifier = encryptedKey.KeyIdentifier;
                byte[] wrappedKey = encryptedKey.GetWrappedKey();
                WrappedKeySecurityToken wrappedKeyToken = CreateWrappedKeyToken(encryptedKey.Id, encryptedKey.EncryptionMethod, 
                    encryptedKey.CarriedKeyName, unwrappingTokenIdentifier, wrappedKey, tokenResolver);
                wrappedKeyToken.EncryptedKey = encryptedKey; 
 
                return wrappedKeyToken;
            } 

            WrappedKeySecurityToken CreateWrappedKeyToken(string id, string encryptionMethod, string carriedKeyName,
                SecurityKeyIdentifier unwrappingTokenIdentifier, byte[] wrappedKey, SecurityTokenResolver tokenResolver)
            { 
                ISspiNegotiationInfo sspiResolver = tokenResolver as ISspiNegotiationInfo;
                if (sspiResolver != null) 
                { 
                    ISspiNegotiation unwrappingSspiContext = sspiResolver.SspiNegotiation;
                    // ensure that the encryption algorithm is compatible 
                    if (encryptionMethod != unwrappingSspiContext.KeyEncryptionAlgorithm)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.BadKeyEncryptionAlgorithm, encryptionMethod)));
                    } 
                    byte[] unwrappedKey = unwrappingSspiContext.Decrypt(wrappedKey);
                    return new WrappedKeySecurityToken(id, unwrappedKey, encryptionMethod, unwrappingSspiContext, unwrappedKey); 
                } 
                else
                { 
                    if (tokenResolver == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("tokenResolver"));
                    } 
                    if (unwrappingTokenIdentifier == null || unwrappingTokenIdentifier.Count == 0)
                    { 
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.MissingKeyInfoInEncryptedKey))); 
                    }
 
                    SecurityToken unwrappingToken;
                    SecurityHeaderTokenResolver resolver = tokenResolver as SecurityHeaderTokenResolver;
                    if (resolver != null)
                    { 
                        unwrappingToken = resolver.ExpectedWrapper;
                        if (unwrappingToken != null) 
                        { 
                            if (!resolver.CheckExternalWrapperMatch(unwrappingTokenIdentifier))
                            { 
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
                                    SR.GetString(SR.EncryptedKeyWasNotEncryptedWithTheRequiredEncryptingToken, unwrappingToken)));
                            }
                        } 
                        else
                        { 
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException( 
                                SR.GetString(SR.UnableToResolveKeyInfoForUnwrappingToken, unwrappingTokenIdentifier, resolver)));
                        } 
                    }
                    else
                    {
                        try 
                        {
                            unwrappingToken = tokenResolver.ResolveToken(unwrappingTokenIdentifier); 
                        } 
                        catch (Exception exception)
                        { 
                            if (exception is MessageSecurityException)
                                throw;

                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException( 
                                SR.GetString(SR.UnableToResolveKeyInfoForUnwrappingToken, unwrappingTokenIdentifier, tokenResolver), exception));
                        } 
                    } 
                    SecurityKey unwrappingSecurityKey;
                    byte[] unwrappedKey = SecurityUtils.DecryptKey(unwrappingToken, encryptionMethod, wrappedKey, out unwrappingSecurityKey); 
                    return new WrappedKeySecurityToken(id, unwrappedKey, encryptionMethod, unwrappingToken, unwrappingTokenIdentifier, wrappedKey, unwrappingSecurityKey);
                }
            }
 
            public override void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token)
            { 
                WrappedKeySecurityToken wrappedKeyToken = token as WrappedKeySecurityToken; 
                wrappedKeyToken.EnsureEncryptedKeySetUp();
                wrappedKeyToken.EncryptedKey.SecurityTokenSerializer = this.tokenSerializer; 
                wrappedKeyToken.EncryptedKey.WriteTo(writer, ServiceModelDictionaryManager.Instance);
            }
        }
 
        protected class X509TokenEntry : BinaryTokenEntry
        { 
            internal const string ValueTypeAbsoluteUri = SecurityJan2004Strings.X509TokenType; 

            public X509TokenEntry(WSSecurityTokenSerializer tokenSerializer) 
                : base(tokenSerializer, ValueTypeAbsoluteUri)
            {
            }
 
            protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(X509SecurityToken), typeof(X509WindowsSecurityToken) }; }
 
            public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromBinaryCore(byte[] rawData) 
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.CantInferReferenceForToken, ValueTypeAbsoluteUri))); 
            }

            public override SecurityToken ReadBinaryCore(string id, byte[] rawData)
            { 
                X509Certificate2 certificate;
                if (!SecurityUtils.TryCreateX509CertificateFromRawData(rawData, out certificate)) 
                { 
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.InvalidX509RawData));
                } 
                return new X509SecurityToken(certificate, id, false);
            }

            public override void WriteBinaryCore(SecurityToken token, out string id, out byte[] rawData) 
            {
                id = token.Id; 
                X509SecurityToken x509Token = token as X509SecurityToken; 
                if (x509Token != null)
                { 
                    rawData = x509Token.Certificate.GetRawCertData();
                }
                else
                { 
                    rawData = ((X509WindowsSecurityToken)token).Certificate.GetRawCertData();
                } 
            } 
        }
 
        protected class SecurityTokenReferenceJan2004ClauseEntry : KeyIdentifierClauseEntry
        {
            WSSecurityTokenSerializer tokenSerializer;
            IList strEntries; 

            public SecurityTokenReferenceJan2004ClauseEntry(WSSecurityTokenSerializer tokenSerializer, IList strEntries) 
            { 
                this.tokenSerializer = tokenSerializer;
                this.strEntries = strEntries; 
            }

            protected override XmlDictionaryString LocalName
            { 
                get
                { 
                    return XD.SecurityJan2004Dictionary.SecurityTokenReference; 
                }
            } 

            protected override XmlDictionaryString NamespaceUri
            {
                get 
                {
                    return XD.SecurityJan2004Dictionary.Namespace; 
                } 
            }
 
            protected virtual string ReadTokenType(XmlDictionaryReader reader)
            {
                return null;
            } 

            public override SecurityKeyIdentifierClause ReadKeyIdentifierClauseCore(XmlDictionaryReader reader) 
            { 
                byte[] nonce = null;
                int length = 0; 
                if (reader.IsStartElement(XD.SecurityJan2004Dictionary.SecurityTokenReference, NamespaceUri))
                {
                    string nonceString = reader.GetAttribute(XD.SecureConversationFeb2005Dictionary.Nonce, XD.SecureConversationFeb2005Dictionary.Namespace);
                    if (nonceString != null) 
                    {
                        nonce = Convert.FromBase64String(nonceString); 
                    } 

                    string lengthString = reader.GetAttribute(XD.SecureConversationFeb2005Dictionary.Length, XD.SecureConversationFeb2005Dictionary.Namespace); 
                    if (lengthString != null)
                    {
                        length = Convert.ToInt32(lengthString, CultureInfo.InvariantCulture);
                    } 
                    else
                    { 
                        length = DerivedKeySecurityToken.DefaultDerivedKeyLength; 
                    }
                } 
                string tokenType = ReadTokenType(reader);
                reader.ReadStartElement(XD.SecurityJan2004Dictionary.SecurityTokenReference, NamespaceUri);
                SecurityKeyIdentifierClause clause = null;
                for (int i = 0; i < this.strEntries.Count; ++i) 
                {
                    if (this.strEntries[i].CanReadClause(reader, tokenType)) 
                    { 
                        clause = this.strEntries[i].ReadClause(reader, nonce, length, tokenType);
                        break; 
                    }
                }

                if (clause == null) 
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.CannotReadKeyIdentifierClause, reader.LocalName, reader.NamespaceURI))); 
                } 

                reader.ReadEndElement(); 
                return clause;
            }

            public override bool SupportsCore(SecurityKeyIdentifierClause keyIdentifierClause) 
            {
                for (int i = 0; i < this.strEntries.Count; ++i) 
                { 
                    if (this.strEntries[i].SupportsCore(keyIdentifierClause))
                    { 
                        return true;
                    }
                }
                return false; 
            }
 
            public override void WriteKeyIdentifierClauseCore(XmlDictionaryWriter writer, SecurityKeyIdentifierClause keyIdentifierClause) 
            {
                for (int i = 0; i < this.strEntries.Count; ++i) 
                {
                    if (this.strEntries[i].SupportsCore(keyIdentifierClause))
                    {
                        writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.SecurityTokenReference, XD.SecurityJan2004Dictionary.Namespace); 
                        this.strEntries[i].WriteContent(writer, keyIdentifierClause);
                        writer.WriteEndElement(); 
                        return; 
                    }
                } 
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.StandardsManagerCannotWriteObject, keyIdentifierClause.GetType())));
            }
        }
 
        protected abstract class KeyIdentifierStrEntry : StrEntry
        { 
            WSSecurityTokenSerializer tokenSerializer; 

            protected const string EncodingTypeValueBase64Binary = SecurityJan2004Strings.EncodingTypeValueBase64Binary; 
            protected const string EncodingTypeValueHexBinary = SecurityJan2004Strings.EncodingTypeValueHexBinary;
            protected const string EncodingTypeValueText = SecurityJan2004Strings.EncodingTypeValueText;

            protected abstract Type ClauseType { get; } 
            protected virtual string DefaultEncodingType { get { return EncodingTypeValueBase64Binary; } }
            public abstract Type TokenType { get; } 
            protected abstract string ValueTypeUri { get; } 

            protected KeyIdentifierStrEntry(WSSecurityTokenSerializer tokenSerializer) 
            {
                this.tokenSerializer = tokenSerializer;
            }
 
            public override bool CanReadClause(XmlDictionaryReader reader, string tokenType)
            { 
                if (reader.IsStartElement(XD.SecurityJan2004Dictionary.KeyIdentifier, XD.SecurityJan2004Dictionary.Namespace)) 
                {
                    string valueType = reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null); 
                    return (ValueTypeUri == valueType);
                }
                return false;
            } 

            protected abstract SecurityKeyIdentifierClause CreateClause(byte[] bytes, byte[] derivationNonce, int derivationLength); 
 
            public override Type GetTokenType(SecurityKeyIdentifierClause clause)
            { 
                return this.TokenType;
            }

            public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNonce, int derivationLength, string tokenType) 
            {
                string encodingType = reader.GetAttribute(XD.SecurityJan2004Dictionary.EncodingType, null); 
                if (encodingType == null) 
                {
                    encodingType = DefaultEncodingType; 
                }

                reader.ReadStartElement();
 
                byte[] bytes;
                if (encodingType == EncodingTypeValueBase64Binary) 
                { 
                    bytes = reader.ReadContentAsBase64();
                } 
                else if (encodingType == EncodingTypeValueHexBinary)
                {
                    bytes = HexBinary.Parse(reader.ReadContentAsString()).Value;
                } 
                else if (encodingType == EncodingTypeValueText)
                { 
                    bytes = new UTF8Encoding().GetBytes(reader.ReadContentAsString()); 
                }
                else 
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.UnknownEncodingInKeyIdentifier)));
                }
 
                reader.ReadEndElement();
 
                return CreateClause(bytes, derivationNonce, derivationLength); 
            }
 
            public override bool SupportsCore(SecurityKeyIdentifierClause clause)
            {
                return ClauseType.IsAssignableFrom(clause.GetType());
            } 

            public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause) 
            { 
                writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.KeyIdentifier, XD.SecurityJan2004Dictionary.Namespace);
                writer.WriteAttributeString(XD.SecurityJan2004Dictionary.ValueType, null, ValueTypeUri); 
                if (this.tokenSerializer.EmitBspRequiredAttributes)
                {
                    // Emit the encodingType attribute.
                    writer.WriteAttributeString(XD.SecurityJan2004Dictionary.EncodingType, null, DefaultEncodingType); 
                }
                string encoding = DefaultEncodingType; 
                BinaryKeyIdentifierClause binaryClause = clause as BinaryKeyIdentifierClause; 

                byte[] keyIdentifier = binaryClause.GetBuffer(); 
                if (encoding == EncodingTypeValueBase64Binary)
                {
                    writer.WriteBase64(keyIdentifier, 0, keyIdentifier.Length);
                } 
                else if (encoding == EncodingTypeValueHexBinary)
                { 
                    writer.WriteBinHex(keyIdentifier, 0, keyIdentifier.Length); 
                }
                else if (encoding == EncodingTypeValueText) 
                {
                    writer.WriteString(new UTF8Encoding().GetString(keyIdentifier, 0, keyIdentifier.Length));
                }
                writer.WriteEndElement(); 
            }
        } 
 
        class KerberosHashStrEntry : KeyIdentifierStrEntry
        { 
            protected override Type ClauseType { get { return typeof(KerberosTicketHashKeyIdentifierClause); } }
            public override Type TokenType { get { return typeof(KerberosRequestorSecurityToken); } }
            protected override string ValueTypeUri  {  get { return SecurityJan2004Strings.KerberosHashValueType; } }
 
            public KerberosHashStrEntry(WSSecurityTokenSerializer tokenSerializer)
                : base(tokenSerializer) 
            { 
            }
 
            protected override SecurityKeyIdentifierClause CreateClause(byte[] bytes, byte[] derivationNonce, int derivationLength)
            {
                return new KerberosTicketHashKeyIdentifierClause(bytes, derivationNonce, derivationLength);
            } 
        }
 
        class X509SkiStrEntry : KeyIdentifierStrEntry 
        {
            protected override Type ClauseType { get { return typeof(X509SubjectKeyIdentifierClause); } } 
            public override Type TokenType { get {  return typeof(X509SecurityToken);  }  }
            protected override string ValueTypeUri { get {  return SecurityJan2004Strings.X509SKIValueType; }  }

            public X509SkiStrEntry(WSSecurityTokenSerializer tokenSerializer) 
                : base(tokenSerializer)
            { 
            } 

            protected override SecurityKeyIdentifierClause CreateClause(byte[] bytes, byte[] derivationNonce, int derivationLength) 
            {
                return new X509SubjectKeyIdentifierClause(bytes);
            }
        } 

        class LocalReferenceStrEntry : StrEntry 
        { 
            WSSecurityTokenSerializer tokenSerializer;
 
            public LocalReferenceStrEntry(WSSecurityTokenSerializer tokenSerializer)
            {
                this.tokenSerializer = tokenSerializer;
            } 

            public override Type GetTokenType(SecurityKeyIdentifierClause clause) 
            { 
                LocalIdKeyIdentifierClause localClause = clause as LocalIdKeyIdentifierClause;
                return localClause.OwnerType; 
            }

            public override bool CanReadClause(XmlDictionaryReader reader, string tokenType)
            { 
                if (reader.IsStartElement(XD.SecurityJan2004Dictionary.Reference, XD.SecurityJan2004Dictionary.Namespace))
                { 
                    string uri = reader.GetAttribute(XD.SecurityJan2004Dictionary.URI, null); 
                    if (uri != null && uri.Length > 0 && uri[0] == '#')
                    { 
                        return true;
                    }
                }
                return false; 
            }
 
            public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNonce, int derivationLength, string tokenType) 
            {
                string uri = reader.GetAttribute(XD.SecurityJan2004Dictionary.URI, null); 
                string tokenTypeUri = reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null);
                Type[] tokenTypes = null;
                if (tokenTypeUri != null)
                { 
                    tokenTypes = this.tokenSerializer.GetTokenTypes(tokenTypeUri);
                } 
                SecurityKeyIdentifierClause clause = new LocalIdKeyIdentifierClause(uri.Substring(1), derivationNonce, derivationLength, tokenTypes); 
                if (reader.IsEmptyElement)
                { 
                    reader.Read();
                }
                else
                { 
                    reader.ReadStartElement();
                    reader.ReadEndElement(); 
                } 
                return clause;
            } 

            public override bool SupportsCore(SecurityKeyIdentifierClause clause)
            {
                return clause is LocalIdKeyIdentifierClause; 
            }
 
            public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause) 
            {
                LocalIdKeyIdentifierClause localIdClause = clause as LocalIdKeyIdentifierClause; 
                writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.Reference, XD.SecurityJan2004Dictionary.Namespace);
                if (this.tokenSerializer.EmitBspRequiredAttributes)
                {
                    Type tokenType = GetTokenType(clause); 
                    string tokenTypeUri = this.tokenSerializer.GetTokenTypeUri(tokenType);
                    if (tokenTypeUri != null) 
                    { 
                        writer.WriteAttributeString(XD.SecurityJan2004Dictionary.ValueType, null, tokenTypeUri);
                    } 
                }
                writer.WriteAttributeString(XD.SecurityJan2004Dictionary.URI, null, "#" + localIdClause.LocalId);
                writer.WriteEndElement();
            } 
        }
 
        protected class SamlJan2004KeyIdentifierStrEntry : StrEntry 
        {
            protected virtual bool IsMatchingValueType(string valueType) 
            {
                return (valueType == SecurityJan2004Strings.SamlAssertionIdValueType);
            }
 
            public override bool CanReadClause(XmlDictionaryReader reader, string tokenType)
            { 
                if (reader.IsStartElement(XD.SamlDictionary.AuthorityBinding, XD.SecurityJan2004Dictionary.SamlUri)) 
                {
                    return true; 
                }
                else if (reader.IsStartElement(XD.SecurityJan2004Dictionary.KeyIdentifier, XD.SecurityJan2004Dictionary.Namespace))
                {
                    string valueType = reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null); 
                    return IsMatchingValueType(valueType);
                } 
                return false; 
            }
 
            public override Type GetTokenType(SecurityKeyIdentifierClause clause)
            {
                return typeof(SamlSecurityToken);
            } 

            public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNone, int derivationLength, string tokenType) 
            { 
                bool readAuthorityBinding = false;
                bool readKeyIdentifier = false; 
                string id = null;
                string valueType = null;
                string binding = null;
                string location = null; 
                string authorityKind = null;
                while (reader.IsStartElement()) 
                { 
                    if (reader.IsStartElement(XD.SamlDictionary.AuthorityBinding, XD.SecurityJan2004Dictionary.SamlUri))
                    { 
                        if (readAuthorityBinding)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MultipleSamlAuthorityBindingsInReference)));
                        } 
                        readAuthorityBinding = true;
                        binding = reader.GetAttribute(XD.SamlDictionary.Binding, null); 
                        if (string.IsNullOrEmpty(binding)) 
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.RequiredAttributeMissing, XD.SamlDictionary.Binding.Value, XD.SamlDictionary.AuthorityBinding.Value))); 
                        }
                        location = reader.GetAttribute(XD.SamlDictionary.Location, null);
                        if (string.IsNullOrEmpty(location))
                        { 
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.RequiredAttributeMissing, XD.SamlDictionary.Location.Value, XD.SamlDictionary.AuthorityBinding.Value)));
                        } 
                        authorityKind = reader.GetAttribute(XD.SamlDictionary.AuthorityKind, null); 
                        if (string.IsNullOrEmpty(authorityKind))
                        { 
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.RequiredAttributeMissing, XD.SamlDictionary.AuthorityKind.Value, XD.SamlDictionary.AuthorityBinding.Value)));
                        }
                        if (reader.IsEmptyElement)
                        { 
                            reader.Read();
                        } 
                        else 
                        {
                            reader.ReadStartElement(); 
                            reader.ReadEndElement();
                        }
                    }
                    else if (reader.IsStartElement(XD.SecurityJan2004Dictionary.KeyIdentifier, XD.SecurityJan2004Dictionary.Namespace)) 
                    {
                        if (readKeyIdentifier) 
                        { 
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MultipleKeyIdentifiersInReference)));
                        } 
                        readKeyIdentifier = true;
                        valueType = reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null);
                        id = reader.ReadElementContentAsString();
                    } 
                    else
                    { 
                        break; 
                    }
                } 
                if (!readKeyIdentifier)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.DidNotFindKeyIdentifierInReference)));
                } 
                return new SamlAssertionKeyIdentifierClause(id, derivationNone, derivationLength, valueType, tokenType, binding, location, authorityKind);
            } 
 
            public override bool SupportsCore(SecurityKeyIdentifierClause clause)
            { 
                return typeof(SamlAssertionKeyIdentifierClause).IsAssignableFrom(clause.GetType());
            }

            public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause) 
            {
                SamlAssertionKeyIdentifierClause samlClause = clause as SamlAssertionKeyIdentifierClause; 
                if (!string.IsNullOrEmpty(samlClause.Binding) || !string.IsNullOrEmpty(samlClause.Location) || !string.IsNullOrEmpty(samlClause.AuthorityKind)) 
                {
                    writer.WriteStartElement(XD.SamlDictionary.PreferredPrefix.Value, XD.SamlDictionary.AuthorityBinding, XD.SecurityJan2004Dictionary.SamlUri); 
                    if (!string.IsNullOrEmpty(samlClause.Binding))
                    {
                        writer.WriteAttributeString(XD.SamlDictionary.Binding, null, samlClause.Binding);
                    } 
                    if (!string.IsNullOrEmpty(samlClause.Location))
                    { 
                        writer.WriteAttributeString(XD.SamlDictionary.Location, null, samlClause.Location); 
                    }
                    if (!string.IsNullOrEmpty(samlClause.AuthorityKind)) 
                    {
                        writer.WriteAttributeString(XD.SamlDictionary.AuthorityKind, null, samlClause.AuthorityKind);
                    }
                    writer.WriteEndElement(); 
                }
                writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.KeyIdentifier, XD.SecurityJan2004Dictionary.Namespace); 
                string valueType = string.IsNullOrEmpty(samlClause.ValueType) ? XD.SecurityJan2004Dictionary.SamlAssertionIdValueType.Value : samlClause.ValueType; 
                writer.WriteAttributeString(XD.SecurityJan2004Dictionary.ValueType, null, valueType);
                writer.WriteString(samlClause.AssertionId); 
                writer.WriteEndElement();
            }
        }
 
        class RelDirectStrEntry : StrEntry
        { 
            public override bool CanReadClause(XmlDictionaryReader reader, string tokenType) 
            {
                if (reader.IsStartElement(XD.SecurityJan2004Dictionary.Reference, XD.SecurityJan2004Dictionary.Namespace)) 
                {
                    string valueType = reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null);
                    return (valueType == SecurityJan2004Strings.RelAssertionValueType);
                } 
                return false;
            } 
 
            public override Type GetTokenType(SecurityKeyIdentifierClause clause)
            { 
                return null;
            }

            public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNone, int derivationLength, string tokenType) 
            {
                string assertionId = reader.GetAttribute(XD.SecurityJan2004Dictionary.URI, null); 
                if (reader.IsEmptyElement) 
                {
                    reader.Read(); 
                }
                else
                {
                    reader.ReadStartElement(); 
                    reader.ReadEndElement();
                } 
                return new RelAssertionDirectKeyIdentifierClause(assertionId, derivationNone, derivationLength); 
            }
 
            public override bool SupportsCore(SecurityKeyIdentifierClause clause)
            {
                return typeof(RelAssertionDirectKeyIdentifierClause).IsAssignableFrom(clause.GetType());
            } 

            public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause) 
            { 
                RelAssertionDirectKeyIdentifierClause relClause = clause as RelAssertionDirectKeyIdentifierClause;
                writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.Reference, XD.SecurityJan2004Dictionary.Namespace); 
                writer.WriteAttributeString(XD.SecurityJan2004Dictionary.ValueType, null, SecurityJan2004Strings.RelAssertionValueType);
                writer.WriteAttributeString(XD.SecurityJan2004Dictionary.URI, null, relClause.AssertionId);
                writer.WriteEndElement();
            } 
        }
 
        class X509IssuerSerialStrEntry : StrEntry 
        {
            public override Type GetTokenType(SecurityKeyIdentifierClause clause) 
            {
                return typeof(X509SecurityToken);
            }
 
            public override bool CanReadClause(XmlDictionaryReader reader, string tokenType)
            { 
                return reader.IsStartElement(XD.XmlSignatureDictionary.X509Data, XD.XmlSignatureDictionary.Namespace); 
            }
 
            public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNonce, int derivationLength, string tokenType)
            {
                reader.ReadStartElement(XD.XmlSignatureDictionary.X509Data, XD.XmlSignatureDictionary.Namespace);
                reader.ReadStartElement(XD.XmlSignatureDictionary.X509IssuerSerial, XD.XmlSignatureDictionary.Namespace); 
                reader.ReadStartElement(XD.XmlSignatureDictionary.X509IssuerName, XD.XmlSignatureDictionary.Namespace);
                string issuerName = reader.ReadContentAsString(); 
                reader.ReadEndElement(); 
                reader.ReadStartElement(XD.XmlSignatureDictionary.X509SerialNumber, XD.XmlSignatureDictionary.Namespace);
                string serialNumber = reader.ReadContentAsString(); 
                reader.ReadEndElement();
                reader.ReadEndElement();
                reader.ReadEndElement();
 
                return new X509IssuerSerialKeyIdentifierClause(issuerName, serialNumber);
            } 
 
            public override bool SupportsCore(SecurityKeyIdentifierClause clause)
            { 
                return clause is X509IssuerSerialKeyIdentifierClause;
            }

            public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause) 
            {
                X509IssuerSerialKeyIdentifierClause issuerClause = clause as X509IssuerSerialKeyIdentifierClause; 
                writer.WriteStartElement(XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509Data, XD.XmlSignatureDictionary.Namespace); 
                writer.WriteStartElement(XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509IssuerSerial, XD.XmlSignatureDictionary.Namespace);
                writer.WriteElementString(XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509IssuerName, XD.XmlSignatureDictionary.Namespace, issuerClause.IssuerName); 
                writer.WriteElementString(XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509SerialNumber, XD.XmlSignatureDictionary.Namespace, issuerClause.IssuerSerialNumber);
                writer.WriteEndElement();
                writer.WriteEndElement();
            } 
        }
 
        public class IdManager : SignatureTargetIdManager 
        {
            static readonly IdManager instance = new IdManager(); 

            IdManager()
            {
            } 

            public override string DefaultIdNamespacePrefix 
            { 
                get { return UtilityStrings.Prefix; }
            } 

            public override string DefaultIdNamespaceUri
            {
                get { return UtilityStrings.Namespace; } 
            }
 
            internal static IdManager Instance 
            {
                get { return instance; } 
            }

            public override string ExtractId(XmlDictionaryReader reader)
            { 
                if (reader == null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); 
 
                if (reader.IsStartElement(EncryptedData.ElementName, XD.XmlEncryptionDictionary.Namespace))
                { 
                    return reader.GetAttribute(XD.XmlEncryptionDictionary.Id, null);
                }
                else
                { 
                    return reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace);
                } 
            } 

            public override void WriteIdAttribute(XmlDictionaryWriter writer, string id) 
            {
                if (writer == null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
 
                writer.WriteAttributeString(XD.UtilityDictionary.Prefix.Value, XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace, id);
            } 
        } 
    }
} 

// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
// Copyright (c) Microsoft Corporation. All rights reserved.


                        

Link Menu

Network programming in C#, Network Programming in VB.NET, Network Programming in .NET
This book is available now!
Buy at Amazon US or
Buy at Amazon UK