void WriteEncryptedKeyIdentifierClause(
     XmlWriter w, EncryptedKeyIdentifierClause ic)
 {
     w.WriteStartElement("e", "EncryptedKey", EncryptedXml.XmlEncNamespaceUrl);
     w.WriteStartElement("EncryptionMethod", EncryptedXml.XmlEncNamespaceUrl);
     w.WriteAttributeString("Algorithm", ic.EncryptionMethod);
     w.WriteEndElement();
     if (ic.EncryptingKeyIdentifier != null)
     {
         w.WriteStartElement("KeyInfo", SignedXml.XmlDsigNamespaceUrl);
         foreach (SecurityKeyIdentifierClause ckic in ic.EncryptingKeyIdentifier)
         {
             WriteKeyIdentifierClause(w, ckic);
         }
         w.WriteEndElement();
     }
     w.WriteStartElement("CipherData", EncryptedXml.XmlEncNamespaceUrl);
     w.WriteStartElement("CipherValue", EncryptedXml.XmlEncNamespaceUrl);
     w.WriteString(Convert.ToBase64String(ic.GetEncryptedKey()));
     w.WriteEndElement();
     w.WriteEndElement();
     if (ic.CarriedKeyName != null)
     {
         w.WriteElementString("CarriedKeyName", EncryptedXml.XmlEncNamespaceUrl, ic.CarriedKeyName);
     }
     w.WriteEndElement();
 }
            public override void WriteKeyIdentifierClauseCore(XmlDictionaryWriter writer, SecurityKeyIdentifierClause keyIdentifierClause)
            {
                EncryptedKeyIdentifierClause clause = keyIdentifierClause as EncryptedKeyIdentifierClause;

                writer.WriteStartElement(XD.XmlEncryptionDictionary.Prefix.Value, XD.XmlEncryptionDictionary.EncryptedKey, this.NamespaceUri);
                if (clause.EncryptionMethod != null)
                {
                    writer.WriteStartElement(XD.XmlEncryptionDictionary.Prefix.Value, XD.XmlEncryptionDictionary.EncryptionMethod, this.NamespaceUri);
                    writer.WriteAttributeString(XD.XmlEncryptionDictionary.AlgorithmAttribute, null, clause.EncryptionMethod);
                    if (clause.EncryptionMethod == XD.SecurityAlgorithmDictionary.RsaOaepKeyWrap.Value)
                    {
                        writer.WriteStartElement("", XD.XmlSignatureDictionary.DigestMethod, XD.XmlSignatureDictionary.Namespace);
                        writer.WriteAttributeString(XD.XmlSignatureDictionary.Algorithm, null, "http://www.w3.org/2000/09/xmldsig#sha1");
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();
                }
                if (clause.EncryptingKeyIdentifier != null)
                {
                    this.tokenSerializer.WriteKeyIdentifier(writer, clause.EncryptingKeyIdentifier);
                }
                writer.WriteStartElement(XD.XmlEncryptionDictionary.Prefix.Value, XD.XmlEncryptionDictionary.CipherData, this.NamespaceUri);
                writer.WriteStartElement(XD.XmlEncryptionDictionary.Prefix.Value, XD.XmlEncryptionDictionary.CipherValue, this.NamespaceUri);
                byte[] encryptedKey = clause.GetEncryptedKey();
                writer.WriteBase64(encryptedKey, 0, encryptedKey.Length);
                writer.WriteEndElement();
                writer.WriteEndElement();
                if (clause.CarriedKeyName != null)
                {
                    writer.WriteElementString(XD.XmlEncryptionDictionary.Prefix.Value, XD.XmlEncryptionDictionary.CarriedKeyName, this.NamespaceUri, clause.CarriedKeyName);
                }
                writer.WriteEndElement();
            }
Пример #3
0
 private bool TryResolveTokenFromIntrinsicKeyClause(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityToken token)
 {
     token = null;
     if (keyIdentifierClause is RsaKeyIdentifierClause)
     {
         token = new RsaSecurityToken(((RsaKeyIdentifierClause)keyIdentifierClause).Rsa);
         return(true);
     }
     if (keyIdentifierClause is X509RawDataKeyIdentifierClause)
     {
         token = new X509SecurityToken(new X509Certificate2(((X509RawDataKeyIdentifierClause)keyIdentifierClause).GetX509RawData()), false);
         return(true);
     }
     if (keyIdentifierClause is EncryptedKeyIdentifierClause)
     {
         SecurityToken token2;
         EncryptedKeyIdentifierClause keyClause = (EncryptedKeyIdentifierClause)keyIdentifierClause;
         SecurityKeyIdentifier        encryptingKeyIdentifier = keyClause.EncryptingKeyIdentifier;
         if (base.TryResolveToken(encryptingKeyIdentifier, out token2))
         {
             token = System.ServiceModel.Security.SecurityUtils.CreateTokenFromEncryptedKeyClause(keyClause, token2);
             return(true);
         }
     }
     return(false);
 }
Пример #4
0
        /// <summary>
        /// Creates a SAML Token with the input parameters
        /// </summary>
        /// <param name="stsName">Name of the STS issuing the SAML Token</param>
        /// <param name="proofToken">Associated Proof Token</param>
        /// <param name="issuerToken">Associated Issuer Token</param>
        /// <param name="proofKeyEncryptionToken">Token to encrypt the proof key with</param>
        /// <param name="samlConditions">The Saml Conditions to be used in the construction of the SAML Token</param>
        /// <param name="samlAttributes">The Saml Attributes to be used in the construction of the SAML Token</param>
        /// <returns>A SAML Token</returns>
        public static SamlSecurityToken CreateSamlToken(string stsName,
                                                        BinarySecretSecurityToken proofToken,
                                                        SecurityToken issuerToken,
                                                        SecurityToken proofKeyEncryptionToken,
                                                        SamlConditions samlConditions,
                                                        IEnumerable <SamlAttribute> samlAttributes)
        {
            // Create a security token reference to the issuer certificate
            SecurityKeyIdentifierClause skic = issuerToken.CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>();
            SecurityKeyIdentifier       issuerKeyIdentifier = new SecurityKeyIdentifier(skic);

            // Create an encrypted key clause containing the encrypted proof key
            byte[] wrappedKey = proofKeyEncryptionToken.SecurityKeys[0].EncryptKey(SecurityAlgorithms.RsaOaepKeyWrap, proofToken.GetKeyBytes());
            SecurityKeyIdentifierClause  encryptingTokenClause = proofKeyEncryptionToken.CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>();
            EncryptedKeyIdentifierClause encryptedKeyClause    = new EncryptedKeyIdentifierClause(wrappedKey, SecurityAlgorithms.RsaOaepKeyWrap, new SecurityKeyIdentifier(encryptingTokenClause));
            SecurityKeyIdentifier        proofKeyIdentifier    = new SecurityKeyIdentifier(encryptedKeyClause);

            // Create a comfirmationMethod for HolderOfKey
            List <string> confirmationMethods = new List <string>(1);

            confirmationMethods.Add(SamlConstants.HolderOfKey);

            // Create a SamlSubject with proof key and confirmation method from above
            SamlSubject samlSubject = new SamlSubject(null,
                                                      null,
                                                      null,
                                                      confirmationMethods,
                                                      null,
                                                      proofKeyIdentifier);

            // Create a SamlAttributeStatement from the passed in SamlAttribute collection and the SamlSubject from above
            SamlAttributeStatement samlAttributeStatement = new SamlAttributeStatement(samlSubject, samlAttributes);

            // Put the SamlAttributeStatement into a list of SamlStatements
            List <SamlStatement> samlSubjectStatements = new List <SamlStatement>();

            samlSubjectStatements.Add(samlAttributeStatement);

            // Create a SigningCredentials instance from the key associated with the issuerToken.
            SigningCredentials signingCredentials = new SigningCredentials(issuerToken.SecurityKeys[0],
                                                                           SecurityAlgorithms.RsaSha1Signature,
                                                                           SecurityAlgorithms.Sha1Digest,
                                                                           issuerKeyIdentifier);

            // Create a SamlAssertion from the list of SamlStatements created above and the passed in
            // SamlConditions.
            SamlAssertion samlAssertion = new SamlAssertion("_" + Guid.NewGuid().ToString(),
                                                            stsName,
                                                            DateTime.UtcNow,
                                                            samlConditions,
                                                            new SamlAdvice(),
                                                            samlSubjectStatements
                                                            );

            // Set the SigningCredentials for the SamlAssertion
            samlAssertion.SigningCredentials = signingCredentials;

            // Create a SamlSecurityToken from the SamlAssertion and return it
            return(new SamlSecurityToken(samlAssertion));
        }
        public void Constructors()
        {
            byte [] bytes = new byte [32];
            // null identifier / null CarriedKeyName
            EncryptedKeyIdentifierClause ekic =
                new EncryptedKeyIdentifierClause(bytes, SecurityAlgorithms.Aes256Encryption, null, null);

            Assert.IsNull(ekic.EncryptingKeyIdentifier, "#1");
            Assert.IsNull(ekic.CarriedKeyName, "#2");

            // any EncryptionMethods are allowed here..
            new EncryptedKeyIdentifierClause(new byte [32], "urn:foo");
        }
Пример #6
0
        internal static XmlDocument GetPlainAsertion(SecurityTokenResolver securityTokenResolver, XmlElement el)
        {
            var encryptedDataElement = GetElement(HttpRedirectBindingConstants.EncryptedData, Saml20Constants.Xenc, el);

            var encryptedData = new System.Security.Cryptography.Xml.EncryptedData();

            encryptedData.LoadXml(encryptedDataElement);
            var encryptedKey        = new System.Security.Cryptography.Xml.EncryptedKey();
            var encryptedKeyElement = GetElement(HttpRedirectBindingConstants.EncryptedKey, Saml20Constants.Xenc, el);

            encryptedKey.LoadXml(encryptedKeyElement);
            var securityKeyIdentifier = new SecurityKeyIdentifier();

            foreach (KeyInfoX509Data v in encryptedKey.KeyInfo)
            {
                foreach (X509Certificate2 cert in v.Certificates)
                {
                    var cl = new X509RawDataKeyIdentifierClause(cert);
                    securityKeyIdentifier.Add(cl);
                }
            }

            var         clause = new EncryptedKeyIdentifierClause(encryptedKey.CipherData.CipherValue, encryptedKey.EncryptionMethod.KeyAlgorithm, securityKeyIdentifier);
            SecurityKey key;
            var         success = securityTokenResolver.TryResolveSecurityKey(clause, out key);

            if (!success)
            {
                throw new InvalidOperationException("Cannot locate security key");
            }

            SymmetricSecurityKey symmetricSecurityKey = key as SymmetricSecurityKey;

            if (symmetricSecurityKey == null)
            {
                throw new InvalidOperationException("Key must be symmentric key");
            }

            SymmetricAlgorithm symmetricAlgorithm = symmetricSecurityKey.GetSymmetricAlgorithm(encryptedData.EncryptionMethod.KeyAlgorithm);
            var encryptedXml = new System.Security.Cryptography.Xml.EncryptedXml();

            var plaintext = encryptedXml.DecryptData(encryptedData, symmetricAlgorithm);
            var assertion = new XmlDocument {
                PreserveWhitespace = true
            };

            assertion.Load(new StringReader(Encoding.UTF8.GetString(plaintext)));
            return(assertion);
        }
Пример #7
0
            protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
            {
                if (keyIdentifierClause == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause");
                }

                key = null;
                for (int i = 0; i < _tokens.Count; ++i)
                {
                    SecurityKey securityKey = _tokens[i].ResolveKeyIdentifierClause(keyIdentifierClause);
                    if (securityKey != null)
                    {
                        key = securityKey;
                        return(true);
                    }
                }

                if (keyIdentifierClause is EncryptedKeyIdentifierClause)
                {
                    EncryptedKeyIdentifierClause keyClause     = (EncryptedKeyIdentifierClause)keyIdentifierClause;
                    SecurityKeyIdentifier        keyIdentifier = keyClause.EncryptingKeyIdentifier;
                    if (keyIdentifier != null && keyIdentifier.Count > 0)
                    {
                        for (int i = 0; i < keyIdentifier.Count; i++)
                        {
                            SecurityKey unwrappingSecurityKey = null;
                            if (TryResolveSecurityKey(keyIdentifier[i], out unwrappingSecurityKey))
                            {
                                byte[] wrappedKey        = keyClause.GetEncryptedKey();
                                string wrappingAlgorithm = keyClause.EncryptionMethod;
                                byte[] unwrappedKey      = unwrappingSecurityKey.DecryptKey(wrappingAlgorithm, wrappedKey);
                                key = new InMemorySymmetricSecurityKey(unwrappedKey, false);
                                return(true);
                            }
                        }
                    }
                }

                return(key != null);
            }
Пример #8
0
    /// <summary>
    /// Resolves the given SecurityKeyIdentifierClause to a SecurityKey.
    /// </summary>
    /// <param name="keyIdentifierClause">SecurityKeyIdentifierClause to resolve</param>
    /// <param name="key">The resolved SecurityKey.</param>
    /// <returns>True if successfully resolved.</returns>
    /// <exception cref="ArgumentNullException">The input argument 'keyIdentifierClause' is null.</exception>
    protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
    {
        if (keyIdentifierClause == null)
        {
            throw new ArgumentNullException("keyIdentifierClause");
        }

        key = null;
        EncryptedKeyIdentifierClause encryptedKeyIdentifierClause = keyIdentifierClause as EncryptedKeyIdentifierClause;

        if (encryptedKeyIdentifierClause != null)
        {
            SecurityKeyIdentifier keyIdentifier = encryptedKeyIdentifierClause.EncryptingKeyIdentifier;
            if (keyIdentifier != null && keyIdentifier.Count > 0)
            {
                for (int i = 0; i < keyIdentifier.Count; i++)
                {
                    SecurityKey unwrappingSecurityKey = null;
                    if (TryResolveSecurityKey(keyIdentifier[i], out unwrappingSecurityKey))
                    {
                        key = new InMemorySymmetricSecurityKey(unwrappingSecurityKey.DecryptKey(encryptedKeyIdentifierClause.EncryptionMethod, encryptedKeyIdentifierClause.GetEncryptedKey()), false);
                        return(true);
                    }
                }
            }
        }
        else
        {
            SecurityToken token = null;
            if (TryResolveToken(keyIdentifierClause, out token))
            {
                if (token.SecurityKeys.Count > 0)
                {
                    key = token.SecurityKeys[0];
                    return(true);
                }
            }
        }

        return(false);
    }
 protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
 {
     if (keyIdentifierClause == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause");
     }
     key = null;
     for (int i = 0; i < this.tokens.Count; i++)
     {
         SecurityKey key2 = this.tokens[i].ResolveKeyIdentifierClause(keyIdentifierClause);
         if (key2 != null)
         {
             key = key2;
             return(true);
         }
     }
     if (keyIdentifierClause is EncryptedKeyIdentifierClause)
     {
         EncryptedKeyIdentifierClause clause = (EncryptedKeyIdentifierClause)keyIdentifierClause;
         SecurityKeyIdentifier        encryptingKeyIdentifier = clause.EncryptingKeyIdentifier;
         if ((encryptingKeyIdentifier != null) && (encryptingKeyIdentifier.Count > 0))
         {
             for (int j = 0; j < encryptingKeyIdentifier.Count; j++)
             {
                 SecurityKey key3 = null;
                 if (base.TryResolveSecurityKey(encryptingKeyIdentifier[j], out key3))
                 {
                     byte[] encryptedKey     = clause.GetEncryptedKey();
                     string encryptionMethod = clause.EncryptionMethod;
                     byte[] symmetricKey     = key3.DecryptKey(encryptionMethod, encryptedKey);
                     key = new InMemorySymmetricSecurityKey(symmetricKey, false);
                     return(true);
                 }
             }
         }
     }
     return(key != null);
 }
        internal SecurityToken ResolveToken(SecurityKeyIdentifierClause keyIdentifierClause, bool matchOnlyExternal, bool resolveIntrinsicKeyClause)
        {
            if (keyIdentifierClause == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause");
            }

            SecurityToken resolvedToken = null;

            for (int i = 0; i < this.tokenCount; i++)
            {
                if (matchOnlyExternal && tokens[i].AllowedReferenceStyle != SecurityTokenReferenceStyle.External)
                {
                    continue;
                }

                SecurityToken token = tokens[i].Token;
                if (tokens[i].TokenParameters != null && tokens[i].TokenParameters.MatchesKeyIdentifierClause(token, keyIdentifierClause, tokens[i].AllowedReferenceStyle))
                {
                    resolvedToken = token;
                    break;
                }
                else if (tokens[i].TokenParameters == null)
                {
                    // match it according to the allowed reference style
                    if (tokens[i].AllowedReferenceStyle == SecurityTokenReferenceStyle.Internal && MatchDirectReference(token, keyIdentifierClause))
                    {
                        resolvedToken = token;
                        break;
                    }
                }
            }

            if ((resolvedToken == null) && (keyIdentifierClause is EncryptedKeyIdentifierClause))
            {
                EncryptedKeyIdentifierClause keyClause = (EncryptedKeyIdentifierClause)keyIdentifierClause;
                SecurityKeyIdentifier        wrappingTokenReference = keyClause.EncryptingKeyIdentifier;
                SecurityToken unwrappingToken;
                if (this.expectedWrapper != null &&
                    CheckExternalWrapperMatch(wrappingTokenReference))
                {
                    unwrappingToken = this.expectedWrapper;
                }
                else
                {
                    unwrappingToken = ResolveToken(wrappingTokenReference, true, resolveIntrinsicKeyClause);
                }
                if (unwrappingToken != null)
                {
                    resolvedToken = SecurityUtils.CreateTokenFromEncryptedKeyClause(keyClause, unwrappingToken);
                }
            }

            if ((resolvedToken == null) && (keyIdentifierClause is X509RawDataKeyIdentifierClause) && (!matchOnlyExternal) && (resolveIntrinsicKeyClause))
            {
                resolvedToken = new X509SecurityToken(new X509Certificate2(((X509RawDataKeyIdentifierClause)keyIdentifierClause).GetX509RawData()));
            }

            byte[] derivationNonce = keyIdentifierClause.GetDerivationNonce();
            if ((resolvedToken != null) && (derivationNonce != null))
            {
                // A Implicit Derived Key is specified. Create a derived key off of the resolve token.
                if (SecurityUtils.GetSecurityKey <SymmetricSecurityKey>(resolvedToken) == null)
                {
                    // The resolved token contains no Symmetric Security key and thus we cannot create
                    // a derived key off of it.
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.UnableToDeriveKeyFromKeyInfoClause, keyIdentifierClause, resolvedToken)));
                }

                int derivationLength = (keyIdentifierClause.DerivationLength == 0) ? DerivedKeySecurityToken.DefaultDerivedKeyLength : keyIdentifierClause.DerivationLength;
                if (derivationLength > this.securityHeader.MaxDerivedKeyLength)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.DerivedKeyLengthSpecifiedInImplicitDerivedKeyClauseTooLong, keyIdentifierClause.ToString(), derivationLength, this.securityHeader.MaxDerivedKeyLength)));
                }
                bool alreadyDerived = false;
                for (int i = 0; i < this.tokenCount; ++i)
                {
                    DerivedKeySecurityToken derivedKeyToken = this.tokens[i].Token as DerivedKeySecurityToken;
                    if (derivedKeyToken != null)
                    {
                        if ((derivedKeyToken.Length == derivationLength) &&
                            (CryptoHelper.IsEqual(derivedKeyToken.Nonce, derivationNonce)) &&
                            (derivedKeyToken.TokenToDerive.MatchesKeyIdentifierClause(keyIdentifierClause)))
                        {
                            // This is a implcit derived key for which we have already derived the
                            // token.
                            resolvedToken  = this.tokens[i].Token;
                            alreadyDerived = true;
                            break;
                        }
                    }
                }

                if (!alreadyDerived)
                {
                    string psha1Algorithm = SecurityUtils.GetKeyDerivationAlgorithm(this.securityHeader.StandardsManager.MessageSecurityVersion.SecureConversationVersion);

                    resolvedToken = new DerivedKeySecurityToken(-1, 0, derivationLength, null, derivationNonce, resolvedToken, keyIdentifierClause, psha1Algorithm, SecurityUtils.GenerateId());
                    ((DerivedKeySecurityToken)resolvedToken).InitializeDerivedKey(derivationLength);
                    Add(resolvedToken, SecurityTokenReferenceStyle.Internal, null);
                    this.securityHeader.EnsureDerivedKeyLimitNotReached();
                }
            }

            return(resolvedToken);
        }
Пример #11
0
        internal SecurityToken ResolveToken(SecurityKeyIdentifierClause keyIdentifierClause, bool matchOnlyExternal, bool resolveIntrinsicKeyClause)
        {
            if (keyIdentifierClause == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause");
            }
            SecurityToken token = null;

            for (int i = 0; i < this.tokenCount; i++)
            {
                if (!matchOnlyExternal || (this.tokens[i].AllowedReferenceStyle == SecurityTokenReferenceStyle.External))
                {
                    SecurityToken token2 = this.tokens[i].Token;
                    if ((this.tokens[i].TokenParameters != null) && this.tokens[i].TokenParameters.MatchesKeyIdentifierClause(token2, keyIdentifierClause, this.tokens[i].AllowedReferenceStyle))
                    {
                        token = token2;
                        break;
                    }
                    if (((this.tokens[i].TokenParameters == null) && (this.tokens[i].AllowedReferenceStyle == SecurityTokenReferenceStyle.Internal)) && this.MatchDirectReference(token2, keyIdentifierClause))
                    {
                        token = token2;
                        break;
                    }
                }
            }
            if ((token == null) && (keyIdentifierClause is EncryptedKeyIdentifierClause))
            {
                SecurityToken expectedWrapper;
                EncryptedKeyIdentifierClause keyClause = (EncryptedKeyIdentifierClause)keyIdentifierClause;
                SecurityKeyIdentifier        encryptingKeyIdentifier = keyClause.EncryptingKeyIdentifier;
                if ((this.expectedWrapper != null) && this.CheckExternalWrapperMatch(encryptingKeyIdentifier))
                {
                    expectedWrapper = this.expectedWrapper;
                }
                else
                {
                    expectedWrapper = this.ResolveToken(encryptingKeyIdentifier, true, resolveIntrinsicKeyClause);
                }
                if (expectedWrapper != null)
                {
                    token = System.ServiceModel.Security.SecurityUtils.CreateTokenFromEncryptedKeyClause(keyClause, expectedWrapper);
                }
            }
            if (((token == null) && (keyIdentifierClause is X509RawDataKeyIdentifierClause)) && (!matchOnlyExternal && resolveIntrinsicKeyClause))
            {
                token = new X509SecurityToken(new X509Certificate2(((X509RawDataKeyIdentifierClause)keyIdentifierClause).GetX509RawData()));
            }
            byte[] derivationNonce = keyIdentifierClause.GetDerivationNonce();
            if ((token != null) && (derivationNonce != null))
            {
                if (System.ServiceModel.Security.SecurityUtils.GetSecurityKey <SymmetricSecurityKey>(token) == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("UnableToDeriveKeyFromKeyInfoClause", new object[] { keyIdentifierClause, token })));
                }
                int length = (keyIdentifierClause.DerivationLength == 0) ? 0x20 : keyIdentifierClause.DerivationLength;
                if (length > this.securityHeader.MaxDerivedKeyLength)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("DerivedKeyLengthSpecifiedInImplicitDerivedKeyClauseTooLong", new object[] { keyIdentifierClause.ToString(), length, this.securityHeader.MaxDerivedKeyLength })));
                }
                bool flag = false;
                for (int j = 0; j < this.tokenCount; j++)
                {
                    DerivedKeySecurityToken token4 = this.tokens[j].Token as DerivedKeySecurityToken;
                    if (((token4 != null) && (token4.Length == length)) && (CryptoHelper.IsEqual(token4.Nonce, derivationNonce) && token4.TokenToDerive.MatchesKeyIdentifierClause(keyIdentifierClause)))
                    {
                        token = this.tokens[j].Token;
                        flag  = true;
                        break;
                    }
                }
                if (!flag)
                {
                    string keyDerivationAlgorithm = System.ServiceModel.Security.SecurityUtils.GetKeyDerivationAlgorithm(this.securityHeader.StandardsManager.MessageSecurityVersion.SecureConversationVersion);
                    token = new DerivedKeySecurityToken(-1, 0, length, null, derivationNonce, token, keyIdentifierClause, keyDerivationAlgorithm, System.ServiceModel.Security.SecurityUtils.GenerateId());
                    ((DerivedKeySecurityToken)token).InitializeDerivedKey(length);
                    this.Add(token, SecurityTokenReferenceStyle.Internal, null);
                    this.securityHeader.EnsureDerivedKeyLimitNotReached();
                }
            }
            return(token);
        }