public void ComputeSignature(SecurityKey signingKey)
 {
     string signatureMethod = this.Signature.SignedInfo.SignatureMethod;
     SymmetricSecurityKey key = signingKey as SymmetricSecurityKey;
     if (key != null)
     {
         using (KeyedHashAlgorithm algorithm = key.GetKeyedHashAlgorithm(signatureMethod))
         {
             if (algorithm == null)
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.IdentityModel.SR.GetString("UnableToCreateKeyedHashAlgorithm", new object[] { key, signatureMethod })));
             }
             this.ComputeSignature(algorithm);
             return;
         }
     }
     AsymmetricSecurityKey key2 = signingKey as AsymmetricSecurityKey;
     if (key2 == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.IdentityModel.SR.GetString("UnknownICryptoType", new object[] { signingKey })));
     }
     using (HashAlgorithm algorithm2 = key2.GetHashAlgorithmForSignature(signatureMethod))
     {
         if (algorithm2 == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.IdentityModel.SR.GetString("UnableToCreateHashAlgorithmFromAsymmetricCrypto", new object[] { signatureMethod, key2 })));
         }
         AsymmetricSignatureFormatter signatureFormatter = key2.GetSignatureFormatter(signatureMethod);
         if (signatureFormatter == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.IdentityModel.SR.GetString("UnableToCreateSignatureFormatterFromAsymmetricCrypto", new object[] { signatureMethod, key2 })));
         }
         this.ComputeSignature(algorithm2, signatureFormatter, signatureMethod);
     }
 }
 private void InitCrypto(SecurityKey securityKey)
 {
     m_securityKey = securityKey;
     List<SecurityKey> securityKeys = new List<SecurityKey>(1);
     securityKeys.Add(securityKey);
     m_securityKeys = securityKeys.AsReadOnly();
 }
示例#3
0
		public SigningCredentials (SecurityKey signingKey, string signatureAlgorithm, string digestAlgorithm, SecurityKeyIdentifier signingKeyIdentifier)
			: this (signingKey, signatureAlgorithm, digestAlgorithm)
		{
			if (signingKeyIdentifier == null)
				throw new ArgumentNullException ("signingKeyIdentifier");
			this.identifier = signingKeyIdentifier;
		}
        /// <summary>
        /// Inherited from <see cref="SecurityTokenResolver"/>.
        /// </summary>
        protected override bool TryResolveSecurityKeyCore( SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key )
        {
            if ( keyIdentifierClause == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "keyIdentifierClause" );
            }

            key = null;

            X509RawDataKeyIdentifierClause rawDataClause = keyIdentifierClause as X509RawDataKeyIdentifierClause;
            if ( rawDataClause != null )
            {
                key = rawDataClause.CreateKey();
                return true;
            }

            RsaKeyIdentifierClause rsaClause = keyIdentifierClause as RsaKeyIdentifierClause;
            if ( rsaClause != null )
            {
                key = rsaClause.CreateKey();
                return true;
            }

            if ( _wrappedTokenResolver.TryResolveSecurityKey( keyIdentifierClause, out key ) )
            {
                return true;
            }

            return false;
        }
        /// <summary>
        /// Constructs an EncryptingCredentials with a security key, a security key identifier and
        /// the encryption algorithm.
        /// </summary>
        /// <param name="key">A security key for encryption.</param>
        /// <param name="keyIdentifier">A security key identifier for the encryption key.</param>
        /// <param name="algorithm">The encryption algorithm.</param>
        /// <exception cref="ArgumentNullException">When key is null.</exception>
        /// <exception cref="ArgumentNullException">When key identifier is null.</exception>
        /// <exception cref="ArgumentNullException">When algorithm is null.</exception>
        public EncryptingCredentials(SecurityKey key, SecurityKeyIdentifier keyIdentifier, string algorithm)
        {
            if (key == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("key");
            }

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

            if (string.IsNullOrEmpty(algorithm))
            {
                throw DiagnosticUtility.ThrowHelperArgumentNullOrEmptyString("algorithm");
            }

            //
            // It is possible that keyIdentifier is pointing to a token which 
            // is not capable of doing the given algorithm, we have no way verify 
            // that at this level.
            //
            _algorithm = algorithm;
            _key = key;
            _keyIdentifier = keyIdentifier;
        }
 public bool TryResolveSecurityKey(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
 {
     if (keyIdentifierClause == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause");
     }
     return this.TryResolveSecurityKeyCore(keyIdentifierClause, out key);
 }
		public SwtIssuerTokenResolver()
		{
			var signValue = ConfigurationManager.AppSettings[SigningKeyAppSetting];
			if (string.IsNullOrEmpty(signValue))
				throw new InvalidSecurityException(string.Format(
					"Required appSettings key '{0}' containing the 256-bit symmetric key for token signing was not found.",
					SigningKeyAppSetting));

			this.key = new InMemorySymmetricSecurityKey(Convert.FromBase64String(signValue));
		}
		protected BinarySecretSecurityToken (string id, byte [] key, bool allowCrypto)
			: this (id, allowCrypto)
		{
			if (key == null)
				throw new ArgumentNullException ("key");
			this.key = key;

			SecurityKey [] arr = new SecurityKey [] {new InMemorySymmetricSecurityKey (key)};
			keys = new ReadOnlyCollection<SecurityKey> (arr);
		}
		protected override bool TryResolveSecurityKeyCore (
			SecurityKeyIdentifierClause keyIdentifierClause,
			out SecurityKey key)
		{
			key = null;
			foreach (SecurityTokenResolver r in resolvers)
				if (r != null && r.TryResolveSecurityKey (keyIdentifierClause, out key))
					return true;
			return false;
		}
 protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
 {
     SecurityToken token;
     if (this.TryResolveTokenCore(keyIdentifierClause, out token))
     {
         key = ((SecurityContextSecurityToken) token).SecurityKeys[0];
         return true;
     }
     key = null;
     return false;
 }
示例#11
0
		public SigningCredentials (SecurityKey signingKey, string signatureAlgorithm, string digestAlgorithm)
		{
			if (signingKey == null)
				throw new ArgumentNullException ("signingKey");
			if (signatureAlgorithm == null)
				throw new ArgumentNullException ("signatureAlgorithm");
			if (digestAlgorithm == null)
				throw new ArgumentNullException ("digestAlgorithm");
			this.key = signingKey;
			this.sig_alg = signatureAlgorithm;
			this.dig_alg = digestAlgorithm;
		}
		protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
		{
			// We pass ourselves a SwtSecurityKeyClause from the SwtSecurityTokenHandler on ValidateToken.
			var nameClause = keyIdentifierClause as SwtSecurityKeyClause;

			// If it wasn't us passing the clause, let the base class handle other built-in scenarios (i.e. X509)
			if (nameClause == null)
				return base.TryResolveSecurityKeyCore(keyIdentifierClause, out key);

			key = this.key;
			return true;
		}
        protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
        {
            key = null;
            var swtClause = keyIdentifierClause as WebTokenSecurityKeyClause;

            string value;
            if (_signingKeys.TryGetValue(swtClause.Issuer.ToLowerInvariant(), out value))
            {
                key = new InMemorySymmetricSecurityKey(Convert.FromBase64String(value));

                return true;
            }

            return false;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="NamedKeySecurityToken"/> class that contains a single <see cref="SecurityKey"/>.
        /// </summary>
        /// <param name="name">A name for the <see cref="SecurityKey"/>.</param>
        /// <param name="id">the identifier for this token.</param>
        /// <param name="key">A <see cref="SecurityKey"/></param>
        /// <exception cref="ArgumentNullException">if 'name' is null or whitespace.</exception>
        /// <exception cref="ArgumentNullException">if 'id' is null or whitespace.</exception>
        /// <exception cref="ArgumentNullException">if 'key' is null.</exception>
        public NamedKeySecurityToken(string name, string id, SecurityKey key)
        {
            if (string.IsNullOrWhiteSpace(name))
                throw new ArgumentNullException("name");

            if (string.IsNullOrWhiteSpace(id))
                throw new ArgumentNullException("id");

            if (key == null)
                throw new ArgumentNullException("key");

            this.id = id;
            this.name = name;
            this.securityKeys = new List<SecurityKey>{key};
            this.validFrom = DateTime.UtcNow;

        }
        protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
        {
            key = null;
            CustomTokenKeyIdentifierClause keyClause = keyIdentifierClause as CustomTokenKeyIdentifierClause;
            if (keyClause != null)
            {
                string base64Key = null;
                _keys.TryGetValue(keyClause.Audience, out base64Key);
                if (!string.IsNullOrEmpty(base64Key))
                {
                    key = new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes(base64Key));
                    return true;
                }
            }

            return false;
        }
        /// <summary>
        /// Override of the base class. Resolves the given SecurityKeyIdentifierClause to a 
        /// SecurityKey.
        /// </summary>
        /// <param name="keyIdentifierClause">The Clause to be resolved.</param>
        /// <param name="key">The resolved SecurityKey</param>
        /// <returns>True if successfully resolved.</returns>
        /// <exception cref="ArgumentNullException">Input argument 'keyIdentifierClause' is null.</exception>
        protected override bool TryResolveSecurityKeyCore( SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key )
        {
            if ( keyIdentifierClause == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "keyIdentifierClause" );
            }

            key = null;
            foreach ( SecurityTokenResolver tokenResolver in _tokenResolvers )
            {
                if ( tokenResolver.TryResolveSecurityKey( keyIdentifierClause, out key ) )
                {
                    return true;
                }
            }

            return false;
        }
 public SigningCredentials(SecurityKey signingKey, string signatureAlgorithm, string digestAlgorithm, SecurityKeyIdentifier signingKeyIdentifier)
 {
     if (signingKey == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("signingKey"));
     }
     if (signatureAlgorithm == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("signatureAlgorithm"));
     }
     if (digestAlgorithm == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("digestAlgorithm"));
     }
     this.signingKey = signingKey;
     this.signatureAlgorithm = signatureAlgorithm;
     this.digestAlgorithm = digestAlgorithm;
     this.signingKeyIdentifier = signingKeyIdentifier;
 }
        /// <summary>
        /// Creates the JWT header
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="credential">The credentials.</param>
        /// <returns>The JWT header</returns>
        protected virtual async Task<JwtHeader> CreateHeaderAsync(Token token, SecurityKey key)
        {
            JwtHeader header = null;

#if DOTNET5_4
            header = new JwtHeader(new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature));
#elif NET451
            header = new JwtHeader(new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest));

            var x509key = key as X509SecurityKey;
            if (x509key != null)
            {
                header.Add("kid", await _keyService.GetKidAsync(x509key.Certificate));
                header.Add("x5t", await _keyService.GetKidAsync(x509key.Certificate));
            }
#endif

            return header;
        }
        /// <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 DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("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))
                        {
                            byte[] wrappedKey = encryptedKeyIdentifierClause.GetEncryptedKey();
                            string wrappingAlgorithm = encryptedKeyIdentifierClause.EncryptionMethod;
                            byte[] unwrappedKey = unwrappingSecurityKey.DecryptKey(wrappingAlgorithm, wrappedKey);
                            key = new InMemorySymmetricSecurityKey(unwrappedKey, 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)
 {
     bool flag = false;
     key = null;
     flag = this.tokenResolver.TryResolveSecurityKey(keyIdentifierClause, false, out key);
     if (!flag && (this.outOfBandTokenResolvers != null))
     {
         for (int i = 0; i < this.outOfBandTokenResolvers.Count; i++)
         {
             flag = this.outOfBandTokenResolvers[i].TryResolveSecurityKey(keyIdentifierClause, out key);
             if (flag)
             {
                 break;
             }
         }
     }
     if (!flag)
     {
         flag = System.ServiceModel.Security.SecurityUtils.TryCreateKeyFromIntrinsicKeyClause(keyIdentifierClause, this, out key);
     }
     return flag;
 }
        private SignatureProvider CreateProvider(SecurityKey key, string algorithm, bool willCreateSignatures)
        {
            _Logger?.LogDebug($"Creating {algorithm} provider for {key.KeyId} for {(willCreateSignatures ? "signing" : "verifying")}");
            if (key == null)
                throw new ArgumentNullException(nameof(key));
            if (string.IsNullOrWhiteSpace(algorithm))
                throw new ArgumentNullException(nameof(algorithm));

            //AsymmetricSecurityKey asymmetricSecurityKey = key as AsymmetricSecurityKey;
            //if (asymmetricSecurityKey != null)
            //    return new AsymmetricSignatureProvider(asymmetricSecurityKey, algorithm, willCreateSignatures, this.AsymmetricAlgorithmResolver);
            SymmetricSecurityKey symmetricSecurityKey = key as SymmetricSecurityKey;
            if (symmetricSecurityKey != null)
                return new SymmetricSignatureProvider(symmetricSecurityKey, algorithm);
            JsonWebKey jsonWebKey = key as JsonWebKey;
            if (jsonWebKey != null && jsonWebKey.Kty != null)
            {
                //if (jsonWebKey.Kty == "RSA" || jsonWebKey.Kty == "EC")
                //    return new AsymmetricSignatureProvider(key, algorithm, willCreateSignatures, this.AsymmetricAlgorithmResolver);
                if (jsonWebKey.Kty == "oct")
                    return new SymmetricSignatureProvider(key, algorithm);
            }
            throw new ArgumentException($"{typeof(SignatureProvider)} supports: '{typeof(SecurityKey)}' of types: '{typeof(AsymmetricSecurityKey)}' or '{typeof(AsymmetricSecurityKey)}'. SecurityKey received was of type: '{key.GetType()}'.");
        }
示例#22
0
        private static string GetEncryptionAlgorithm(SecurityKey key)
        {
            // If key is null, an exception is thrown.
            if (key == null)
                throw new ArgumentNullException("key");

            // Set encryptionAlgorithm to null.
            string encryptionAlgorithm = null;

            // If the security key supports AES256 use that ...
            if (key.IsSupportedAlgorithm(SecurityAlgorithms.Aes256Encryption))
                encryptionAlgorithm = SecurityAlgorithms.Aes256Encryption;
            // ... otherwise if it supports AES192 use that ...
            else if (key.IsSupportedAlgorithm(SecurityAlgorithms.Aes192Encryption))
                encryptionAlgorithm = SecurityAlgorithms.Aes192Encryption;
            // ... otherwise if it supports AES128 use that ...
            else if (key.IsSupportedAlgorithm(SecurityAlgorithms.Aes128Encryption))
                encryptionAlgorithm = SecurityAlgorithms.Aes128Encryption;

            return encryptionAlgorithm;
        }
示例#23
0
        private static string GetSignatureAlgorithm(SecurityKey key)
        {
            // If key is null, an exception is thrown.
            if (key == null)
                throw new ArgumentNullException("key");

            // Set signatureAlgorithm to null.
            string signatureAlgorithm = null;

            // If the security key supports RsaSha1 then use that ...
            if (key.IsSupportedAlgorithm(SecurityAlgorithms.RsaSha1Signature))
                signatureAlgorithm = SecurityAlgorithms.RsaSha1Signature;
            // ... otherwise if it supports HMACSha1 use that ...
            else if (key.IsSupportedAlgorithm(SecurityAlgorithms.HmacSha1Signature))
                signatureAlgorithm = SecurityAlgorithms.HmacSha1Signature;

            return signatureAlgorithm;
        }
示例#24
0
        private static string GetKeyWrapAlgorithm(SecurityKey key)
        {
            // If key is null, an exception is thrown.
            if (key == null)
                throw new ArgumentNullException("key");

            // Set keywrapAlgorithm to null.
            string keywrapAlgorithm = null;

            // If the security key supports RsaOaep then use that ...
            if (key.IsSupportedAlgorithm(SecurityAlgorithms.RsaOaepKeyWrap))
                keywrapAlgorithm = SecurityAlgorithms.RsaOaepKeyWrap;
            // ... otherwise if it supports RSA15 use that ...
            else if (key.IsSupportedAlgorithm(SecurityAlgorithms.RsaV15KeyWrap))
                keywrapAlgorithm = SecurityAlgorithms.RsaV15KeyWrap;
            // ... otherwise if it supports AES256 use that ...
            else if (key.IsSupportedAlgorithm(SecurityAlgorithms.Aes256KeyWrap))
                keywrapAlgorithm = SecurityAlgorithms.Aes256KeyWrap;
            // ... otherwise if it supports AES192 use that ...
            else if (key.IsSupportedAlgorithm(SecurityAlgorithms.Aes192KeyWrap))
                keywrapAlgorithm = SecurityAlgorithms.Aes192KeyWrap;
            // ... otherwise if it supports AES128 use that ...
            else if (key.IsSupportedAlgorithm(SecurityAlgorithms.Aes128KeyWrap))
                keywrapAlgorithm = SecurityAlgorithms.Aes128KeyWrap;

            return keywrapAlgorithm;
        }
        protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
        {
            key = null;
            var dictBasedClause = keyIdentifierClause as DictionaryBasedKeyIdentifierClause;

            if (dictBasedClause != null)
            {
                return this.keys.TryGetValue(dictBasedClause.Dictionary["Audience"].ToLowerInvariant(), out key);
            }

            return false;
        }
        protected override ISignatureValueSecurityElement CompletePrimarySignatureCore(
            SendSecurityHeaderElement[] signatureConfirmations,
            SecurityToken[] signedEndorsingTokens,
            SecurityToken[] signedTokens,
            SendSecurityHeaderElement[] basicTokens, bool isPrimarySignature)
        {
            if (this.signedXml == null)
            {
                return null;
            }

            SecurityTimestamp timestamp = this.Timestamp;
            if (timestamp != null)
            {
                if (timestamp.Id == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.TimestampToSignHasNoId)));
                }
                HashStream hashStream = TakeHashStream();
                this.StandardsManager.WSUtilitySpecificationVersion.WriteTimestampCanonicalForm(
                    hashStream, timestamp, this.signedInfo.ResourcePool.TakeEncodingBuffer());
                signedInfo.AddReference(timestamp.Id, hashStream.FlushHashAndGetValue());
            }

            if ((this.ShouldSignToHeader) && (this.signatureKey is AsymmetricSecurityKey) && (this.Version.Addressing != AddressingVersion.None))
            {
                if (this.toHeaderHash != null)
                    signedInfo.AddReference(this.toHeaderId, this.toHeaderHash);
                else
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.TransportSecurityRequireToHeader)));
            }

            AddSignatureReference(signatureConfirmations);
            if (isPrimarySignature && this.ShouldProtectTokens)
            {
                AddPrimaryTokenSignatureReference(this.ElementContainer.SourceSigningToken, this.SigningTokenParameters);
            }

            if (this.RequireMessageProtection)
            {
                AddSignatureReference(signedEndorsingTokens, SecurityTokenAttachmentMode.SignedEndorsing);
                AddSignatureReference(signedTokens, SecurityTokenAttachmentMode.Signed);
                AddSignatureReference(basicTokens);
            }

            if (this.signedInfo.ReferenceCount == 0)
            {
                throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.NoPartsOfMessageMatchedPartsToSign)), this.Message);
            }
            try
            {
                this.signedXml.ComputeSignature(this.signatureKey);
                return this.signedXml;
            }
            finally
            {
                this.hashStream = null;
                this.signedInfo = null;
                this.signedXml = null;
                this.signatureKey = null;
                this.effectiveSignatureParts = null;
            }
        }
 protected abstract bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key);
 public override SignatureProvider CreateForSigning(SecurityKey key, string algorithm)
 {
     return(CreateProvider(key, algorithm, true));
 }
            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 securityKey = this.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;
            }
 public override SignatureProvider CreateForVerifying(SecurityKey key, string algorithm)
 {
     return(CreateProvider(key, algorithm, false));
 }
示例#31
0
 public EncryptingCredentials(SecurityKey key, SecurityKeyIdentifier keyIdentifier, string algorithm)
 {
     SecurityKey           = key;
     SecurityKeyIdentifier = keyIdentifier;
     Algorithm             = algorithm;
 }
示例#32
0
        private SecurityToken CreateSAMLToken(DateTime validFrom, DateTime validTo, SecurityKey signingKey, SecurityKeyIdentifier signingKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier )
        {
            // Create list of confirmation strings.
            List<string> confirmations = new List<string>();

            // Add holder-of-key string to list of confirmation strings.
            confirmations.Add("urn:oasis:names:tc:SAML:1.0:cm:holder-of-key");

            // Create SAML subject statement based on issuer member variable, confirmation string collection 
            // local variable and proof key identifier parameter.
            SamlSubject subject = new SamlSubject(null, null, issuer, confirmations, null, proofKeyIdentifier);

            // Create a list of SAML attributes.
            List<SamlAttribute> attributes = new List<SamlAttribute>();

            // Get the claimset to place into the SAML assertion.
            ClaimSet cs = GetClaimSet();

            // Iterate through the claims and add a SamlAttribute for each claim.
            // Note that GetClaimSet call above returns a claimset that only contains PossessProperty claims.
            foreach (Claim c in cs)
                attributes.Add(new SamlAttribute(c));

            // Create list of SAML statements.
            List<SamlStatement> statements = new List<SamlStatement>();

            // Add a SAML attribute statement to the list of statements. An attribute statement is based on 
            // a subject statement and SAML attributes that result from claims.
            statements.Add(new SamlAttributeStatement(subject, attributes));

            // Create a valid from/until condition.
            SamlConditions conditions = new SamlConditions(validFrom, validTo);
            
            // Create the SAML assertion.
            SamlAssertion assertion = new SamlAssertion("_" + Guid.NewGuid().ToString(), issuer, validFrom, conditions, null, statements);

            // Set the signing credentials for the SAML assertion.
            string signatureAlgorithm = GetSignatureAlgorithm(signingKey);
            assertion.SigningCredentials = new SigningCredentials(signingKey, signatureAlgorithm, SecurityAlgorithms.Sha1Digest, signingKeyIdentifier);

            return new SamlSecurityToken(assertion);
        }
示例#33
0
        public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
            }
            if (samlSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlSerializer");
            }
            SamlDictionary samlDictionary = samlSerializer.DictionaryManager.SamlDictionary;

            reader.MoveToContent();
            reader.Read();
            if (reader.IsStartElement(samlDictionary.NameIdentifier, samlDictionary.Namespace))
            {
                this.nameFormat    = reader.GetAttribute(samlDictionary.NameIdentifierFormat, null);
                this.nameQualifier = reader.GetAttribute(samlDictionary.NameIdentifierNameQualifier, null);
                reader.MoveToContent();
                this.name = reader.ReadString();
                if (this.name == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLNameIdentifierMissingIdentifierValueOnRead")));
                }
                reader.MoveToContent();
                reader.ReadEndElement();
            }
            if (reader.IsStartElement(samlDictionary.SubjectConfirmation, samlDictionary.Namespace))
            {
                reader.MoveToContent();
                reader.Read();
                while (reader.IsStartElement(samlDictionary.SubjectConfirmationMethod, samlDictionary.Namespace))
                {
                    string str = reader.ReadString();
                    if (string.IsNullOrEmpty(str))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLBadSchema", new object[] { samlDictionary.SubjectConfirmationMethod.Value })));
                    }
                    this.confirmationMethods.Add(str);
                    reader.MoveToContent();
                    reader.ReadEndElement();
                }
                if (this.confirmationMethods.Count == 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLSubjectConfirmationClauseMissingConfirmationMethodOnRead")));
                }
                if (reader.IsStartElement(samlDictionary.SubjectConfirmationData, samlDictionary.Namespace))
                {
                    reader.MoveToContent();
                    this.confirmationData = reader.ReadString();
                    reader.MoveToContent();
                    reader.ReadEndElement();
                }
                if (reader.IsStartElement(samlSerializer.DictionaryManager.XmlSignatureDictionary.KeyInfo, samlSerializer.DictionaryManager.XmlSignatureDictionary.Namespace))
                {
                    XmlDictionaryReader reader2 = XmlDictionaryReader.CreateDictionaryReader(reader);
                    this.securityKeyIdentifier = SamlSerializer.ReadSecurityKeyIdentifier(reader2, keyInfoSerializer);
                    this.crypto = SamlSerializer.ResolveSecurityKey(this.securityKeyIdentifier, outOfBandTokenResolver);
                    if (this.crypto == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SamlUnableToExtractSubjectKey")));
                    }
                    this.subjectToken = SamlSerializer.ResolveSecurityToken(this.securityKeyIdentifier, outOfBandTokenResolver);
                }
                if ((this.confirmationMethods.Count == 0) && string.IsNullOrEmpty(this.name))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLSubjectRequiresNameIdentifierOrConfirmationMethodOnRead")));
                }
                reader.MoveToContent();
                reader.ReadEndElement();
            }
            reader.MoveToContent();
            reader.ReadEndElement();
        }
		protected override bool TryResolveSecurityKeyCore (
			SecurityKeyIdentifierClause keyIdentifierClause,
			out SecurityKey key)
		{
			throw new NotImplementedException ();
		}
示例#35
0
 public SigningCredentials(SecurityKey signingKey, string signatureAlgorithm, string digestAlgorithm) : this(signingKey, signatureAlgorithm, digestAlgorithm, null)
 {
 }