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");
		}
        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();
                }
            }
        }
        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();
                }
            }
        }
		[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);
		}
        /// <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;
        }
        // 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);
        }