public byte[] SignWithCertificate(string message, byte[] rawData, string password)
        {
            X509Certificate2 x509Certificate = new X509Certificate2(rawData, password);

            if (x509Certificate.PublicKey.Key.KeySize < ClientAssertionCertificate.MinKeySizeInBits)
            {
                throw new ArgumentOutOfRangeException("rawData",
                    string.Format(CultureInfo.InvariantCulture, AdalErrorMessage.CertificateKeySizeTooSmallTemplate, ClientAssertionCertificate.MinKeySizeInBits));
            }

            X509AsymmetricSecurityKey x509Key = new X509AsymmetricSecurityKey(x509Certificate);
            RSACryptoServiceProvider rsa = x509Key.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, true) as RSACryptoServiceProvider;

            RSACryptoServiceProvider newRsa = null;
            try
            {
                newRsa = GetCryptoProviderForSha256(rsa);
                using (SHA256Cng sha = new SHA256Cng())
                {
                    return newRsa.SignData(Encoding.UTF8.GetBytes(message), sha);
                }
            }
            finally
            {
                if (newRsa != null && !ReferenceEquals(rsa, newRsa))
                {
                    newRsa.Dispose();
                }
            }
        }
Esempio n. 2
0
 public override SecurityKey CreateKey()
 {
     if (_key == null)
     {
         if (_certificate == null)
         {
             _certificate = new X509Certificate2(GetBuffer());
         }
         _key = new X509AsymmetricSecurityKey(_certificate);
     }
     return(_key);
 }
 public override SecurityKey CreateKey()
 {
     if (this.key == null)
     {
         if (this.certificate == null)
         {
             this.certificate = new X509Certificate2(base.GetBuffer());
         }
         this.key = new X509AsymmetricSecurityKey(this.certificate);
     }
     return(this.key);
 }
 public override SecurityKey CreateKey()
 {
     if (this.key == null)
     {
         if (this.certificate == null)
         {
             this.certificate = new X509Certificate2(GetBuffer());
         }
         this.key = new X509AsymmetricSecurityKey(this.certificate);
     }
     return this.key;
 }
		public void GetAsymmetricAlgorithm ()
		{
			X509AsymmetricSecurityKey key = new X509AsymmetricSecurityKey (cert);
			string name = EncryptedXml.XmlEncRSA15Url;
			AsymmetricAlgorithm alg = key.GetAsymmetricAlgorithm (name, false);
			Assert.IsNotNull (alg, "#1");
			alg = key.GetAsymmetricAlgorithm (name, true);
			Assert.IsNotNull (alg, "#2");

			key = new X509AsymmetricSecurityKey (cert2);
			alg = key.GetAsymmetricAlgorithm (name, false);
			Assert.IsNotNull (alg, "#3");
		}
Esempio n. 6
0
        private static SigningCredentials GenerateSigningCredentials()
        {
            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            var x509Certificate2 = store.Certificates.Find(X509FindType.FindByThumbprint, "4443BE13F1B67C4D2733FFBF100E4F114B08FFBF", false).OfType<X509Certificate2>().FirstOrDefault();

            // Both signatures work
            var signingToken = new X509AsymmetricSecurityKey(x509Certificate2);
            var securityKeyIdentifier1 = new SecurityKeyIdentifier(new X509RawDataKeyIdentifierClause(x509Certificate2));
            var signingCredentials1 = new SigningCredentials(signingToken, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest, securityKeyIdentifier1);

            //RSACryptoServiceProvider rsa = x509Certificate2.PrivateKey as RSACryptoServiceProvider;
            //RsaSecurityKey rsaKey = new RsaSecurityKey(rsa);
            //X509RawDataKeyIdentifierClause x509RawClause = new X509RawDataKeyIdentifierClause(x509Certificate2);
            //SecurityKeyIdentifier securityKeyIdentifier2 = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { x509RawClause });
            //SigningCredentials signingCredentials2 = new SigningCredentials(rsaKey, SecurityAlgorithms.RsaSha1Signature, SecurityAlgorithms.Sha1Digest, securityKeyIdentifier2);

            return signingCredentials1;
        }
        public static byte[] SignWithCertificate(string message, X509Certificate2 x509Certificate)
        {
            X509AsymmetricSecurityKey x509Key = new X509AsymmetricSecurityKey(x509Certificate);
            RSACryptoServiceProvider rsa = x509Key.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, true) as RSACryptoServiceProvider;

            RSACryptoServiceProvider newRsa = null;
            try
            {
                newRsa = GetCryptoProviderForSha256(rsa);
                using (SHA256Cng sha = new SHA256Cng())
                {
                    return newRsa.SignData(Encoding.UTF8.GetBytes(message), sha);
                }
            }
            finally
            {
                if (newRsa != null && !object.ReferenceEquals(rsa, newRsa))
                {
                    newRsa.Dispose();
                }
            }
        }
		public void IsSupportedAlgorithm ()
		{
			X509AsymmetricSecurityKey key = new X509AsymmetricSecurityKey (cert);
			Assert.IsTrue (key.IsSupportedAlgorithm (EncryptedXml.XmlEncRSA15Url), "#1");
			Assert.IsFalse (key.IsSupportedAlgorithm (SignedXml.XmlDsigDSAUrl), "#2");
			Assert.IsFalse (key.IsSupportedAlgorithm (SignedXml.XmlDsigHMACSHA1Url), "#3");
		}
		[Category ("NotDotNet")] // buggy FormatException occurs instead
		public void GetAsymmetricAlgorithmHMACSHA1 ()
		{
			X509AsymmetricSecurityKey key = new X509AsymmetricSecurityKey (cert);
			key.GetAsymmetricAlgorithm (SignedXml.XmlDsigHMACSHA1Url, false);
		}
		public void GetAsymmetricAlgorithmDSA ()
		{
			X509AsymmetricSecurityKey key = new X509AsymmetricSecurityKey (cert);
			AsymmetricAlgorithm alg = key.GetAsymmetricAlgorithm (SignedXml.XmlDsigDSAUrl, false);
		}
		[Category ("NotDotNet")] // buggy FormatException occurs instead
		public void GetAsymmetricAlgorithmNullAlgName ()
		{
			X509AsymmetricSecurityKey key = new X509AsymmetricSecurityKey (cert);
			key.GetAsymmetricAlgorithm (null, false);
		}
		public void GetAsymmetricAlgorithmWhereNoPrivKey ()
		{
			X509AsymmetricSecurityKey key = new X509AsymmetricSecurityKey (cert2);
			key.GetAsymmetricAlgorithm (EncryptedXml.XmlEncRSA15Url, true);
		}
		public void GetHashAlgorithmForSignatureFine ()
		{
			X509AsymmetricSecurityKey k = new X509AsymmetricSecurityKey (cert);
			k.GetHashAlgorithmForSignature (SignedXml.XmlDsigRSASHA1Url);
			k.GetHashAlgorithmForSignature (SecurityAlgorithms.RsaSha256Signature);
		}
		// huh?
		//[ExpectedException (typeof (ArgumentNullException))]
		public void IsSupportedAlgorithmNullAlgName ()
		{
			X509AsymmetricSecurityKey key = new X509AsymmetricSecurityKey (cert);
			Assert.IsFalse (key.IsSupportedAlgorithm (null));
		}
        /// <summary>
        /// Sign the data with the X509Certificate
        /// </summary>
        /// <param name="signingCertificate">Signing certificate.</param>
        /// <param name="data">Data to be signed.</param>
        /// <returns>RSA SHA 256 Signature</returns>
        public static byte[] SignData(X509Certificate2 signingCertificate, string data)
        {
            X509AsymmetricSecurityKey securityKey = new X509AsymmetricSecurityKey(signingCertificate);

            RSACryptoServiceProvider rsa =
                securityKey.GetAsymmetricAlgorithm("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", true)
                as RSACryptoServiceProvider;

            if (!signingCertificate.HasPrivateKey)
            {
                throw new ArgumentException(string.Format(
                    "Private key is not found in the certificate: {0}",
                    signingCertificate.Subject));
            }

            if (rsa != null)
            {
                rsa.FromXmlString(signingCertificate.PrivateKey.ToXmlString(true));

                if (rsa.CspKeyContainerInfo.ProviderType != 24)
                {
                    System.Security.Cryptography.CspParameters cspParameters =
                        new System.Security.Cryptography.CspParameters
                            {
                                ProviderType = 24,
                                KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName,
                                KeyNumber = (int) rsa.CspKeyContainerInfo.KeyNumber
                            };

                    if (rsa.CspKeyContainerInfo.MachineKeyStore)
                    {
                        cspParameters.Flags = CspProviderFlags.UseMachineKeyStore;
                    }

                    rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cspParameters);
                }
            }

            HashAlgorithm hashAlgo = System.Security.Cryptography.SHA256.Create();
            byte[] signatureInBytes = rsa.SignData(Encoding.UTF8.GetBytes(data), hashAlgo);

            return signatureInBytes;
        }
		SamlSecurityToken GetSamlToken ()
		{
			SamlAssertion a = new SamlAssertion ();
			
			SamlSubject subject = new SamlSubject (
				SamlConstants.UserNameNamespace,
				"urn:myqualifier",
				"myname");
			SamlAttribute attr = new SamlAttribute (Claim.CreateNameClaim ("myname"));
			SamlAttributeStatement statement =
				new SamlAttributeStatement (subject, new SamlAttribute [] {attr});
			a.Statements.Add (statement);
			a.Issuer = "my_hero";

			X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono");
			X509AsymmetricSecurityKey key =
				new X509AsymmetricSecurityKey (cert);
			a.SigningCredentials =
				new SigningCredentials (key,
					SecurityAlgorithms.HmacSha1Signature, 
					SecurityAlgorithms.Sha256Digest);
			XmlDocument doc = new XmlDocument ();
			XmlWriter w = doc.CreateNavigator ().AppendChild ();
			using (XmlDictionaryWriter dw = XmlDictionaryWriter.CreateDictionaryWriter (w)) {
				a.WriteXml (dw, new SamlSerializer (), new MySecurityTokenSerializer ());
			}
Console.Error.WriteLine (doc.OuterXml);
			return new SamlSecurityToken (a);

		}
        // Get the access token via straight http post request doing client credential flow
        private async Task<String> GetAppOnlyAccessTokenWithHttpRequest(string resource, string tenantId)
        {
            /**
             * use the tenant specific endpoint for requesting the app-only access token
             */
            string tokenIssueEndpoint = appConfig.TokenIssueingUri.Replace("common", tenantId);

            /**
             * sign the assertion with the private key
             */
            string certfile = Server.MapPath(appConfig.ClientCertificatePfx);
            X509Certificate2 cert = new X509Certificate2(
                certfile,
                appConfig.ClientCertificatePfxPassword,
                X509KeyStorageFlags.MachineKeySet);

            /**
             * Example building assertion using Json Tokenhandler. 
             * Sort of cheating, but just if someone wonders ... there are always more ways to do something :-)
             */
            Dictionary<string, string> claims = new Dictionary<string, string>()
            {
                { "sub", appConfig.ClientId },
                { "jti", Guid.NewGuid().ToString() },
            };

            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            X509SigningCredentials signingCredentials = new X509SigningCredentials(cert, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);

            JwtSecurityToken selfSignedToken = new JwtSecurityToken(
                appConfig.ClientId,
                tokenIssueEndpoint,
                claims.Select(c => new Claim(c.Key, c.Value)),
                DateTime.UtcNow, 
                DateTime.UtcNow.Add(TimeSpan.FromMinutes(15)),
                signingCredentials);

            string signedAssertion = tokenHandler.WriteToken(selfSignedToken);

            //---- End example with Json Tokenhandler... now to the fun part doing it all ourselves ...

            /**
              * Example building assertion from scratch with Crypto APIs
            */
            JObject clientAssertion = new JObject();
            clientAssertion.Add("aud", tokenIssueEndpoint);
            clientAssertion.Add("iss", appConfig.ClientId);
            clientAssertion.Add("sub", appConfig.ClientId);
            clientAssertion.Add("jti", Guid.NewGuid().ToString());
            clientAssertion.Add("nbf", WebConvert.EpocTime(DateTime.UtcNow + TimeSpan.FromMinutes(-5)));
            clientAssertion.Add("exp", WebConvert.EpocTime(DateTime.UtcNow + TimeSpan.FromMinutes(15)));

            string assertionPayload = clientAssertion.ToString(Newtonsoft.Json.Formatting.None);

            X509AsymmetricSecurityKey x509Key = new X509AsymmetricSecurityKey(cert);
            RSACryptoServiceProvider rsa = x509Key.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, true) as RSACryptoServiceProvider;
            RSACryptoServiceProvider newRsa = GetCryptoProviderForSha256(rsa);
            SHA256Cng sha = new SHA256Cng();

            JObject header = new JObject(new JProperty("alg", "RS256"));
            string thumbprint = WebConvert.Base64UrlEncoded(WebConvert.HexStringToBytes(cert.Thumbprint));
            header.Add(new JProperty("x5t", thumbprint));

            string encodedHeader = WebConvert.Base64UrlEncoded(header.ToString());
            string encodedPayload = WebConvert.Base64UrlEncoded(assertionPayload);

            string signingInput = String.Concat(encodedHeader, ".", encodedPayload);

            byte[] signature = newRsa.SignData(Encoding.UTF8.GetBytes(signingInput), sha);
  
            signedAssertion = string.Format("{0}.{1}.{2}",
                encodedHeader,
                encodedPayload,
                WebConvert.Base64UrlEncoded(signature));

            /**
             * build the request payload
             */
            FormUrlEncodedContent tokenRequestForm;
            tokenRequestForm = new FormUrlEncodedContent(
                new[] { 
                new KeyValuePair<string,string>("resource", appConfig.ExchangeResourceUri),
                new KeyValuePair<string,string>("client_id", appConfig.ClientId),
                new KeyValuePair<string,string>("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),
                new KeyValuePair<string,string>("client_assertion", signedAssertion),
                new KeyValuePair<string,string>("grant_type","client_credentials"),
                }
                );

            /*
             * Do the web request
             */
            HttpClient client = new HttpClient();

            Task<string> requestString = tokenRequestForm.ReadAsStringAsync();
            StringContent requestContent = new StringContent(requestString.Result);
            requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            requestContent.Headers.Add("client-request-id", System.Guid.NewGuid().ToString());
            requestContent.Headers.Add("return-client-request-id", "true");
            requestContent.Headers.Add("UserAgent", "MatthiasLeibmannsAppOnlyAppSampleBeta/0.1");

            HttpResponseMessage response = client.PostAsync(tokenIssueEndpoint, requestContent).Result;
            JObject jsonResponse = JObject.Parse(response.Content.ReadAsStringAsync().Result);
            JsonSerializer jsonSerializer = new JsonSerializer();

            if(response.IsSuccessStatusCode == true)
            { 
                AADClientCredentialSuccessResponse s = (AADClientCredentialSuccessResponse)jsonSerializer.Deserialize(new JTokenReader(jsonResponse), typeof(AADClientCredentialSuccessResponse));
                return s.access_token;
            }

            AADClientCredentialErrorResponse e = (AADClientCredentialErrorResponse)jsonSerializer.Deserialize(new JTokenReader(jsonResponse), typeof(AADClientCredentialErrorResponse));
            throw new Exception(e.error_description);
        }