コード例 #1
0
        private static SigningCredentials SetSigningCredentials <T>(T contract) where T : SamlTokenContract
        {
            SigningCredentials signingCredentials;

            if (contract.UseRsa)
            {
                var rsa = contract.SigningCertificate.PrivateKey as RSACryptoServiceProvider;
                if (rsa == null)
                {
                    throw new InvalidOperationException(
                              "Signing certificate must include private key for RSA signature.");
                }
                var rsaKey    = new RsaSecurityKey(rsa);
                var rsaClause = new RsaKeyIdentifierClause(rsa);
                var ski       = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { rsaClause });
                signingCredentials = new SigningCredentials(rsaKey,
                                                            contract.AlgorithmSuite.DefaultAsymmetricSignatureAlgorithm,
                                                            contract.AlgorithmSuite.DefaultDigestAlgorithm, ski);
            }
            else
            {
                var clause =
                    new X509SecurityToken(contract.SigningCertificate)
                    .CreateKeyIdentifierClause <X509RawDataKeyIdentifierClause>();
                var ski = new SecurityKeyIdentifier(clause);
                signingCredentials = new X509SigningCredentials(contract.SigningCertificate, ski,
                                                                contract.AlgorithmSuite.DefaultAsymmetricSignatureAlgorithm,
                                                                contract.AlgorithmSuite.DefaultDigestAlgorithm);
            }
            return(signingCredentials);
        }
コード例 #2
0
ファイル: SamlUtilities.cs プロジェクト: ogolikhin/blueprint
        public static Saml2SecurityToken CreateSaml2SecurityTokenSigningByRsa(byte[] certificate, string password, params Claim[] claims)
        {
            var descriptor = new SecurityTokenDescriptor();

            var digestAlgorithm    = "http://www.w3.org/2000/09/xmldsig#sha1";
            var signatureAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";

            var signingCert = new X509Certificate2(certificate, password);

            var rsa                = signingCert.PrivateKey as RSACryptoServiceProvider;
            var rsaKey             = new RsaSecurityKey(rsa);
            var rsaClause          = new RsaKeyIdentifierClause(rsa);
            var signingSki         = new SecurityKeyIdentifier(rsaClause);
            var signingCredentials = new SigningCredentials(rsaKey, signatureAlgorithm, digestAlgorithm, signingSki);

            descriptor.TokenType          = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0";
            descriptor.TokenIssuerName    = "CN=app.nhin-hv.com, OU=Domain Control Validated, O=app.nhin-hv.com";
            descriptor.SigningCredentials = signingCredentials;
            descriptor.Subject            = new ClaimsIdentity(claims);
            descriptor.AppliesToAddress   = "http://localhost/RelyingPartyApplication";

            var issueInstant = DateTime.UtcNow;

            descriptor.Lifetime = new Lifetime(issueInstant, issueInstant + TimeSpan.FromHours(8));

            var tokenHandler = new Saml2SecurityTokenHandler();
            var token        = tokenHandler.CreateToken(descriptor) as Saml2SecurityToken;

            return(token);
        }
コード例 #3
0
        private static SecurityKeyIdentifierClause ReadRSAKeyValue(XmlReader reader)
        {
            string rsaXmlElement = reader.ReadInnerXml();

            var rsa = new RSACryptoServiceProvider(); // Do not dispose! Used later when creating key

            rsa.FromXmlString(rsaXmlElement);
            RsaKeyIdentifierClause clause = new RsaKeyIdentifierClause(rsa);

            return(clause);
        }
コード例 #4
0
            public override void WriteKeyIdentifierClauseCore(XmlDictionaryWriter writer, SecurityKeyIdentifierClause keyIdentifierClause)
            {
                RsaKeyIdentifierClause clause = keyIdentifierClause as RsaKeyIdentifierClause;

                writer.WriteStartElement(XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.KeyValue, this.NamespaceUri);
                writer.WriteStartElement(XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.RsaKeyValue, this.NamespaceUri);
                writer.WriteStartElement(XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.Modulus, this.NamespaceUri);
                clause.WriteModulusAsBase64(writer);
                writer.WriteEndElement();
                writer.WriteStartElement(XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.Exponent, this.NamespaceUri);
                clause.WriteExponentAsBase64(writer);
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
コード例 #5
0
        private GenericXmlSecurityToken GenerateSAML2Token()
        {
            var signingCertificatePrivateKey = new X509Certificate2(Settings.Default.CertificatePath,
                                                                    Settings.Default.Passphrase);
            var encryptingCertificatePublicKey = signingCertificatePrivateKey;
            //new X509Certificate2(@"C:\Users\ed2ny1e\Documents\CommonWell\Integration Certificates\McKesson.cer");
            string                   signingAlgorithm   = SignatureAlgorithm.Sha256;
            string                   digestAlgorithm    = DigestAlgorithm.Sha256;
            SigningCredentials       signingCredentials = null;
            SymmetricProofDescriptor proof = CreateSymmetricProofDescriptor(encryptingCertificatePublicKey);

            switch (ComboBoxSigningAlgorithm.SelectedValue.ToString())
            {
            case "SHA1":
                signingAlgorithm = SignatureAlgorithm.Sha1;
                break;

            case "SHA256":
                signingAlgorithm = SignatureAlgorithm.Sha256;
                break;
            }

            switch (ComboBoxDigestAlgorithm.SelectedValue.ToString())
            {
            case "SHA1":
                digestAlgorithm = DigestAlgorithm.Sha1;
                break;

            case "SHA256":
                digestAlgorithm = DigestAlgorithm.Sha256;
                break;
            }

            if (Rsa.IsChecked.HasValue && Rsa.IsChecked.Value)
            {
                var rsa = signingCertificatePrivateKey.PrivateKey as RSACryptoServiceProvider;
                if (rsa != null)
                {
                    var rsaKey    = new RsaSecurityKey(rsa);
                    var rsaClause = new RsaKeyIdentifierClause(rsa);
                    var ski       = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { rsaClause });
                    signingCredentials = new SigningCredentials(rsaKey, signingAlgorithm, digestAlgorithm, ski);
                }
            }
            else
            {
                var clause =
                    new X509SecurityToken(signingCertificatePrivateKey)
                    .CreateKeyIdentifierClause <X509RawDataKeyIdentifierClause>();
                var ski = new SecurityKeyIdentifier(clause);
                signingCredentials = new X509SigningCredentials(signingCertificatePrivateKey, ski, signingAlgorithm,
                                                                digestAlgorithm);
            }

            SecurityTokenDescriptor tokenDescriptor = BuildSAMLDescriptorUsingXspaProfile();

            tokenDescriptor.TokenType          = WSTrust.TokenType;
            tokenDescriptor.SigningCredentials = signingCredentials;

            if (CheckBoxEncrypt.IsChecked.HasValue && CheckBoxEncrypt.IsChecked.Value)
            {
                const string keyWrapAlgorithm      = WSTrust.KeyWrapAlgorithm;
                const string encryptionAlgorithm   = WSTrust.EncryptionAlgorithm;
                var          encryptingCredentials = new EncryptedKeyEncryptingCredentials(encryptingCertificatePublicKey,
                                                                                           keyWrapAlgorithm, WSTrust.KeySize, encryptionAlgorithm);
                tokenDescriptor.EncryptingCredentials = encryptingCredentials;
            }

            switch (ComboBoxConfirmation.SelectedValue.ToString())
            {
            case "holder":
                if (AsymmetricKey.IsChecked != null && (bool)AsymmetricKey.IsChecked)
                {
                    tokenDescriptor.Proof = CreateAsymmetricProofDescriptor(encryptingCertificatePublicKey);
                }
                else
                {
                    tokenDescriptor.Proof = proof;
                }
                break;

            case "sender":
                //TODO
                break;
            }

            var tokenHandler = new CustomSaml2SecurityTokenHandler();

            tokenDescriptor.AddAuthenticationClaims("uurn:oasis:names:tc:SAML:2.0:ac:classes:X509");
            var outputToken = tokenHandler.CreateToken(tokenDescriptor) as Saml2SecurityToken;

            if (outputToken == null)
            {
                throw new Exception("Failed to create Saml2 Security token");
            }

            // turn token into a generic xml security token
            var outputTokenString = outputToken.ToTokenXmlString();

            // create attached and unattached references
            var attachedReference   = tokenHandler.CreateSecurityTokenReference(outputToken, true);
            var unattachedReference = tokenHandler.CreateSecurityTokenReference(outputToken, false);

            GenericXmlSecurityToken xmlToken;

            if (ComboBoxConfirmation.SelectedValue.ToString().Equals("holder"))
            {
                xmlToken = new GenericXmlSecurityToken(
                    GetElement(outputTokenString),
                    new BinarySecretSecurityToken(proof.GetKeyBytes()),
                    DateTime.UtcNow,
                    DateTime.UtcNow.AddHours(1),
                    attachedReference,
                    unattachedReference,
                    new ReadOnlyCollection <IAuthorizationPolicy>(new List <IAuthorizationPolicy>()));
            }
            else
            {
                xmlToken = new GenericXmlSecurityToken(
                    GetElement(outputTokenString),
                    null,
                    DateTime.UtcNow,
                    DateTime.UtcNow.AddHours(8),
                    attachedReference,
                    unattachedReference,
                    new ReadOnlyCollection <IAuthorizationPolicy>(new List <IAuthorizationPolicy>()));
            }
            return(xmlToken);
        }
コード例 #6
0
            protected override BodyWriter GetFirstOutgoingMessageBody(FederatedTokenProviderState negotiationState, out MessageProperties messageProperties)
            {
                messageProperties = null;
                RequestSecurityToken rst = new RequestSecurityToken(this.StandardsManager);

                if (this.addTargetServiceAppliesTo)
                {
                    if (this.MessageVersion.Addressing == AddressingVersion.WSAddressing10)
                    {
                        rst.SetAppliesTo <EndpointAddress10>(
                            EndpointAddress10.FromEndpointAddress(negotiationState.TargetAddress),
                            DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), DataContractSerializerDefaults.MaxItemsInObjectGraph));
                    }
                    else if (this.MessageVersion.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        rst.SetAppliesTo <EndpointAddressAugust2004>(
                            EndpointAddressAugust2004.FromEndpointAddress(negotiationState.TargetAddress),
                            DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), DataContractSerializerDefaults.MaxItemsInObjectGraph));
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, this.MessageVersion.Addressing)));
                    }
                }
                rst.Context = negotiationState.Context;
                if (!this.isKeySizePresentInRstProperties)
                {
                    rst.KeySize = this.keySize;
                }
                Collection <XmlElement> newRequestProperties = new Collection <XmlElement>();

                if (this.requestProperties != null)
                {
                    for (int i = 0; i < this.requestProperties.Count; ++i)
                    {
                        newRequestProperties.Add(this.requestProperties[i]);
                    }
                }
                if (!isKeyTypePresentInRstProperties)
                {
                    XmlElement keyTypeElement = this.StandardsManager.TrustDriver.CreateKeyTypeElement(this.keyType);
                    newRequestProperties.Insert(0, keyTypeElement);
                }
                if (this.keyType == SecurityKeyType.SymmetricKey)
                {
                    byte[] requestorEntropy = negotiationState.GetRequestorEntropy();
                    rst.SetRequestorEntropy(requestorEntropy);
                }
                else if (this.keyType == SecurityKeyType.AsymmetricKey)
                {
                    RsaKeyIdentifierClause rsaClause     = new RsaKeyIdentifierClause(negotiationState.Rsa);
                    SecurityKeyIdentifier  keyIdentifier = new SecurityKeyIdentifier(rsaClause);
                    newRequestProperties.Add(this.StandardsManager.TrustDriver.CreateUseKeyElement(keyIdentifier, this.StandardsManager));
                    RsaSecurityTokenParameters rsaParameters = new RsaSecurityTokenParameters();
                    rsaParameters.InclusionMode      = SecurityTokenInclusionMode.Never;
                    rsaParameters.RequireDerivedKeys = false;
                    SupportingTokenSpecification rsaSpec = new SupportingTokenSpecification(negotiationState.RsaSecurityToken, EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance, SecurityTokenAttachmentMode.Endorsing, rsaParameters);
                    messageProperties = new MessageProperties();
                    SecurityMessageProperty security = new SecurityMessageProperty();
                    security.OutgoingSupportingTokens.Add(rsaSpec);
                    messageProperties.Security = security;
                }
                if (this.keyType == SecurityKeyType.SymmetricKey && this.KeyEntropyMode == SecurityKeyEntropyMode.CombinedEntropy)
                {
                    newRequestProperties.Add(this.StandardsManager.TrustDriver.CreateComputedKeyAlgorithmElement(this.StandardsManager.TrustDriver.ComputedKeyAlgorithm));
                }
                rst.RequestProperties = newRequestProperties;
                rst.MakeReadOnly();
                return(rst);
            }
コード例 #7
0
            protected override BodyWriter GetFirstOutgoingMessageBody(IssuedSecurityTokenProvider.FederatedTokenProviderState negotiationState, out MessageProperties messageProperties)
            {
                messageProperties = null;
                RequestSecurityToken token = new RequestSecurityToken(base.StandardsManager);

                if (this.addTargetServiceAppliesTo)
                {
                    if (this.MessageVersion.Addressing != AddressingVersion.WSAddressing10)
                    {
                        if (this.MessageVersion.Addressing != AddressingVersion.WSAddressingAugust2004)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { this.MessageVersion.Addressing })));
                        }
                        token.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(negotiationState.TargetAddress), DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), 0x10000));
                    }
                    else
                    {
                        token.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(negotiationState.TargetAddress), DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), 0x10000));
                    }
                }
                token.Context = negotiationState.Context;
                if (!this.isKeySizePresentInRstProperties)
                {
                    token.KeySize = this.keySize;
                }
                Collection <XmlElement> collection = new Collection <XmlElement>();

                if (this.requestProperties != null)
                {
                    for (int i = 0; i < this.requestProperties.Count; i++)
                    {
                        collection.Add(this.requestProperties[i]);
                    }
                }
                if (!this.isKeyTypePresentInRstProperties)
                {
                    XmlElement item = base.StandardsManager.TrustDriver.CreateKeyTypeElement(this.keyType);
                    collection.Insert(0, item);
                }
                if (this.keyType == SecurityKeyType.SymmetricKey)
                {
                    byte[] requestorEntropy = negotiationState.GetRequestorEntropy();
                    token.SetRequestorEntropy(requestorEntropy);
                }
                else if (this.keyType == SecurityKeyType.AsymmetricKey)
                {
                    RsaKeyIdentifierClause clause        = new RsaKeyIdentifierClause(negotiationState.Rsa);
                    SecurityKeyIdentifier  keyIdentifier = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { clause });
                    collection.Add(base.StandardsManager.TrustDriver.CreateUseKeyElement(keyIdentifier, base.StandardsManager));
                    RsaSecurityTokenParameters tokenParameters = new RsaSecurityTokenParameters {
                        InclusionMode      = SecurityTokenInclusionMode.Never,
                        RequireDerivedKeys = false
                    };
                    SupportingTokenSpecification specification = new SupportingTokenSpecification(negotiationState.RsaSecurityToken, System.ServiceModel.Security.EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance, SecurityTokenAttachmentMode.Endorsing, tokenParameters);
                    messageProperties = new MessageProperties();
                    SecurityMessageProperty property = new SecurityMessageProperty {
                        OutgoingSupportingTokens = { specification }
                    };
                    messageProperties.Security = property;
                }
                if ((this.keyType == SecurityKeyType.SymmetricKey) && (this.KeyEntropyMode == SecurityKeyEntropyMode.CombinedEntropy))
                {
                    collection.Add(base.StandardsManager.TrustDriver.CreateComputedKeyAlgorithmElement(base.StandardsManager.TrustDriver.ComputedKeyAlgorithm));
                }
                token.RequestProperties = collection;
                token.MakeReadOnly();
                return(token);
            }