public void GetHashAlgorithmForSignatureFine() { X509AsymmetricSecurityKey k = new X509AsymmetricSecurityKey(cert); k.GetHashAlgorithmForSignature(SignedXml.XmlDsigRSASHA1Url); k.GetHashAlgorithmForSignature(SecurityAlgorithms.RsaSha256Signature); }
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(TestResourceHelper.GetFullPathOfResource("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)); }
public byte[] SignWithCertificate(string message, X509Certificate2 certificate) { if (certificate.PublicKey.Key.KeySize < ClientAssertionCertificate.MinKeySizeInBits) { throw new ArgumentOutOfRangeException("rawData", string.Format(CultureInfo.InvariantCulture, AdalErrorMessage.CertificateKeySizeTooSmallTemplate, ClientAssertionCertificate.MinKeySizeInBits)); } X509AsymmetricSecurityKey x509Key = new X509AsymmetricSecurityKey(certificate); 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(); } } }
private static bool Matches(SecurityKeyIdentifierClause keyIdentifierClause, SecurityKey key, CertMatcher certMatcher, out SecurityToken token) { token = null; if (certMatcher != null) { X509SecurityKey x509Key = key as X509SecurityKey; if (x509Key != null) { if (certMatcher(x509Key.Certificate)) { token = new X509SecurityToken(x509Key.Certificate); return(true); } } else { X509AsymmetricSecurityKey x509AsymmKey = key as X509AsymmetricSecurityKey; if (x509AsymmKey != null) { X509Certificate2 cert = _certFieldInfo.GetValue(x509AsymmKey) as X509Certificate2; if (cert != null && certMatcher(cert)) { token = new X509SecurityToken(cert); return(true); } } } } return(false); }
public void IsAsymmetricAlgorithm() { X509AsymmetricSecurityKey key = new X509AsymmetricSecurityKey(cert); Assert.IsTrue(key.IsAsymmetricAlgorithm(EncryptedXml.XmlEncRSA15Url), "#1"); Assert.IsTrue(key.IsAsymmetricAlgorithm(SignedXml.XmlDsigDSAUrl), "#2"); // It is asymmetric but not supported. Assert.IsFalse(key.IsAsymmetricAlgorithm(SignedXml.XmlDsigHMACSHA1Url), "#3"); }
private static X509AsymmetricSecurityKey GetSecurityKey() { var certificate = new X509Certificate2( HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings[CertificatePath]), ConfigurationManager.AppSettings[CertificatePassword]); var securityKey = new X509AsymmetricSecurityKey(certificate); return(securityKey); }
private static void SignSamlAssertion(SamlAssertion assertion) { var certificate2 = GetCertificateFromStore(System.Configuration.ConfigurationManager.AppSettings["TokenSigningCeritificate"]); var securityKey = new X509AsymmetricSecurityKey(certificate2); assertion.SigningCredentials = new SigningCredentials( securityKey, SecurityAlgorithms.RsaSha1Signature, SecurityAlgorithms.Sha1Digest, new SecurityKeyIdentifier(new X509ThumbprintKeyIdentifierClause(certificate2))); }
public Saml2Signer(X509Certificate2 certificate, string signatureAlgorithm = null) { if (certificate == null) { throw new ArgumentNullException(nameof(certificate)); } Certificate = certificate; Key = new X509AsymmetricSecurityKey(certificate); SignatureAlgorithm = signatureAlgorithm; }
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"); }
private static void SignSamlAssertion(SamlAssertion assertion) { var certificate2 = GetCertificateFromStore(StoreLocation.CurrentUser, DateTime.Now, "CN=SamlTokenSigningCertificate"); if (certificate2 != null) { var securityKey = new X509AsymmetricSecurityKey(certificate2); assertion.SigningCredentials = new SigningCredentials( securityKey, SecurityAlgorithms.RsaSha1Signature, SecurityAlgorithms.Sha1Digest, new SecurityKeyIdentifier(new X509ThumbprintKeyIdentifierClause(certificate2))); } }
public byte[] SignWithCertificate(string message, X509Certificate2 certificate) { if (certificate.PublicKey.Key.KeySize < ClientAssertionCertificate.MinKeySizeInBits) { throw new ArgumentOutOfRangeException(nameof(certificate), string.Format(CultureInfo.InvariantCulture, AdalErrorMessage.CertificateKeySizeTooSmallTemplate, ClientAssertionCertificate.MinKeySizeInBits)); } byte[] messageBytes = Encoding.UTF8.GetBytes(message); var x509Key = new X509AsymmetricSecurityKey(certificate); RSA rsa = x509Key.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, true) as RSA; RSACryptoServiceProvider newRsa = null; try { if (rsa is RSACryptoServiceProvider cspRsa) { // For .NET 4.6 and below we get the old RSACryptoServiceProvider implementation as the default. // Try and get an instance of RSACryptoServiceProvider which supports SHA256 newRsa = GetCryptoProviderForSha256(cspRsa); using (var sha = new SHA256Cng()) { return(newRsa.SignData(messageBytes, sha)); } } else { CngKey key = GetCngPrivateKey(certificate); using (RSACng rsaCng = new RSACng(key)) { rsaCng.SignatureHashAlgorithm = CngAlgorithm.Sha256; return(rsaCng.SignData(messageBytes)); } } } finally { // We only want to dispose of the 'newRsa' instance if it is a *different instance* // from the original one that was used to create it. if (newRsa != null && !ReferenceEquals(rsa, newRsa)) { newRsa.Dispose(); } } }
/// <inheritdoc /> public byte[] SignWithCertificate(string message, X509Certificate2 certificate) { if (certificate.PublicKey.Key.KeySize < ClientAssertionCertificateWrapper.MinKeySizeInBits) { throw new ArgumentOutOfRangeException(nameof(certificate), string.Format(CultureInfo.InvariantCulture, MsalErrorMessage.CertificateKeySizeTooSmallTemplate, ClientAssertionCertificateWrapper.MinKeySizeInBits)); } byte[] messageBytes = Encoding.UTF8.GetBytes(message); var x509Key = new X509AsymmetricSecurityKey(certificate); RSA rsa = x509Key.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, true) as RSA; RSACryptoServiceProvider newRsa = null; try { if (rsa is RSACryptoServiceProvider cspRsa) { // For .NET 4.6 and below we get the old RSACryptoServiceProvider implementation as the default. // Try and get an instance of RSACryptoServiceProvider which supports SHA256 newRsa = GetCryptoProviderForSha256(cspRsa); } else { // For .NET Framework 4.7 and onwards the RSACng implementation is the default. // Since we're targeting .NET Framework 4.5, we cannot actually use this type as it was // only introduced with .NET Framework 4.6. // Instead we try and create an RSACryptoServiceProvider based on the private key from the // certificate. newRsa = GetCryptoProviderForSha256(certificate); } using (var sha = new SHA256Cng()) { return(newRsa.SignData(messageBytes, sha)); } } finally { // We only want to dispose of the 'newRsa' instance if it is a *different instance* // from the original one that was used to create it. if (newRsa != null && !ReferenceEquals(rsa, newRsa)) { newRsa.Dispose(); } } }
/// <summary> /// Validate whether the unsigned value is same as signed value /// </summary> /// <param name="uval"> /// The raw input of the string signed using the key /// </param> /// <param name="sval"> /// The signature of the string /// </param> /// <param name="certthumb"> /// The thumbprint of cert used to encrypt token /// </param> /// <returns> /// True if same, false otherwise. /// </returns> private static bool ValidateSig(byte[] uval, byte[] sval, byte[] certthumb) { try { bool ret = false; X509Certificate2[] certx509 = GetEncodingCert(); string certthumbhex = string.Empty; // Get the hexadecimail representation of the certthumbprint for (int i = 0; i < certthumb.Length; i++) { certthumbhex += certthumb[i].ToString("X2"); } for (int c = 0; c < certx509.Length; c++) { // Skip any cert that does not have the same thumbprint as token if (certx509[c].Thumbprint.ToLower() != certthumbhex.ToLower()) { continue; } X509SecurityToken tok = new X509SecurityToken(certx509[c]); if (tok == null) { return(false); } for (int i = 0; i < tok.SecurityKeys.Count; i++) { X509AsymmetricSecurityKey key = tok.SecurityKeys[i] as X509AsymmetricSecurityKey; RSACryptoServiceProvider rsa = key.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, false) as RSACryptoServiceProvider; if (rsa == null) { continue; } ret = rsa.VerifyData(uval, hash, sval); if (ret == true) { return(ret); } } } return(ret); } catch (CryptographicException e) { Console.WriteLine(e.ToStringDescriptive()); return(false); } }
public IHttpActionResult Get() { SecurityKey issuerSigningKey = null; // You can utilize MetadataSerializer class to read signing key from AD federation metadata MetadataSerializer serializer = new MetadataSerializer(); serializer.CertificateValidationMode = X509CertificateValidationMode.None; var metaData = serializer.ReadMetadata(new XmlTextReader(metadataUri)); issuerSigningKey = metaData.SigningCredentials.SigningKey; ////Or you can mannually parse metadata if you want to persist signing key in your service store and use it later XPathDocument xmlReader = new XPathDocument(metadataUri); XPathNavigator navigator = xmlReader.CreateNavigator(); XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable); manager.AddNamespace("", "urn:oasis:names:tc:SAML:2.0:metadata"); manager.AddNamespace("ns1", "urn:oasis:names:tc:SAML:2.0:metadata"); manager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#"); manager.PushScope(); XPathNodeIterator nodes = navigator.Select("//ns1:EntityDescriptor/ns1:RoleDescriptor/ns1:KeyDescriptor[@use='signing']/ds:KeyInfo/ds:X509Data/ds:X509Certificate", manager); nodes.MoveNext(); XPathNavigator nodesNavigator = nodes.Current; //Cert body is base64 encoded in metadata doc X509Certificate2 cert = new X509Certificate2(Convert.FromBase64String(nodesNavigator.InnerXml)); issuerSigningKey = new X509AsymmetricSecurityKey(cert); JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); var validationParameters = new TokenValidationParameters { IssuerSigningKey = issuerSigningKey, ValidAudience = audience, ValidateIssuer = false, ValidateLifetime = true, }; SecurityToken validated; handler.ValidateToken(this.Request.Headers.Authorization.Parameter, validationParameters, out validated); return(Ok(Order.CreateOrders())); }
protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key) { key = null; var kn = keyIdentifierClause as X509RawDataKeyIdentifierClause; if (kn == null) { return(false); } var cert = new X509Certificate2(kn.GetX509RawData()); if (cert == null) { return(false); } key = new X509AsymmetricSecurityKey(cert); return(key != 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); }
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 string GetAssertion( string issuer, string subject, string certLocation, string certPassword, Dictionary <string, string> attributes) { // Create certificate from file. It must contain private key! X509Certificate2 cert = new X509Certificate2(certLocation, certPassword); // The private key contained in the certificate will be used to sign the token. X509AsymmetricSecurityKey signingKey = new X509AsymmetricSecurityKey(cert); SecurityKeyIdentifier ski = new SecurityKeyIdentifier(new X509ThumbprintKeyIdentifierClause(cert)); SamlAssertion assertion = SamlHelper.CreateSamlAssertion(issuer, subject, subject, attributes); assertion.SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha1Signature, SecurityAlgorithms.Sha1Digest, ski); return(SamlHelper.SerializeToken(assertion)); }
public byte[] Sign(byte[] input) { X509Certificate2 x509Certificate2 = new X509Certificate2( Convert.FromBase64String(Keys.DefaultX509Data_2048), Keys.CertPassword, X509KeyStorageFlags.MachineKeySet); X509AsymmetricSecurityKey signSecurityKey = new X509AsymmetricSecurityKey(x509Certificate2); var algorithm = SecurityAlgorithms.RsaSha256Signature; var hash = signSecurityKey.GetHashAlgorithmForSignature(algorithm); var formatter = signSecurityKey.GetSignatureFormatter(algorithm); formatter.SetHashAlgorithm(hash.GetType().ToString()); var sig = formatter.CreateSignature(hash.ComputeHash(input)); return(sig); }
public static SamlSecurityToken CreateSamlToken(string issuedBy, string subject, string attrNamespace, Dictionary <string, string> claims, string certThumbPrint) { SamlAssertion assertion = new SamlAssertion(); assertion.AssertionId = string.Format("icfi_{0}", Guid.NewGuid().ToString()); assertion.Issuer = issuedBy; SamlSubject subj = new SamlSubject(); subj.Name = subject; SamlAttributeStatement samlAttrStatement = new SamlAttributeStatement(); foreach (string claimKey in claims.Keys) { SamlAttribute attr = new SamlAttribute(); attr.Namespace = attrNamespace; attr.AttributeValues.Add(claims[claimKey]); samlAttrStatement.Attributes.Add(attr); } samlAttrStatement.SamlSubject = subj; assertion.Statements.Add(samlAttrStatement); X509Certificate2 cert = GetCertificate(certThumbPrint); X509AsymmetricSecurityKey signingKey = new X509AsymmetricSecurityKey(cert); assertion.SigningCredentials = new SigningCredentials( signingKey, cert.PublicKey.Key.SignatureAlgorithm, SecurityAlgorithms.Sha1Digest, new SecurityKeyIdentifier(new X509ThumbprintKeyIdentifierClause(cert))); SamlSecurityToken samlToken = new SamlSecurityToken(assertion); return(samlToken); }
public bool Verify(byte[] input, byte[] sig) { X509Certificate2 x509Certificate2 = new X509Certificate2( Convert.FromBase64String(Keys.DefaultX509Data_2048), Keys.CertPassword, X509KeyStorageFlags.MachineKeySet); var publicKey = x509Certificate2.Export(X509ContentType.Cert); X509Certificate2 cert = new X509Certificate2(publicKey); X509AsymmetricSecurityKey securityKey = new X509AsymmetricSecurityKey(cert); var algorithm = SecurityAlgorithms.RsaSha256Signature; var hash = securityKey.GetHashAlgorithmForSignature(algorithm); var deformatter = securityKey.GetSignatureDeformatter(algorithm); deformatter.SetHashAlgorithm(hash.GetType().ToString()); return(deformatter.VerifySignature(hash.ComputeHash(input), sig)); }
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 (SHA256 sha = SHA256.Create()) { return(newRsa.SignData(Encoding.UTF8.GetBytes(message), sha)); } } finally { if (newRsa != null && !object.ReferenceEquals(rsa, newRsa)) { newRsa.Dispose(); } } }
public static Saml2SecurityToken CreateSaml2Token(string issuedBy, string subject, Dictionary <string, string> claimValues, string certThumbPrint) { Trace.TraceInformation("Entering CreateSaml2Token with issuedBy '{0}', subject '{1}', and thumbprint '{2}'", issuedBy, subject, certThumbPrint); Saml2Assertion assertion = new Saml2Assertion(new Saml2NameIdentifier(issuedBy)); assertion.Id = new Saml2Id(string.Format("icfi_{0}", Guid.NewGuid().ToString())); //assertion.Issuer = new Saml2NameIdentifier(issuedBy); Saml2Subject subj = new Saml2Subject(); subj.NameId = new Saml2NameIdentifier(subject); assertion.Subject = subj; Saml2AttributeStatement samlAttrStatement = new Saml2AttributeStatement(); foreach (string claimKey in claimValues.Keys) { samlAttrStatement.Attributes.Add(new Saml2Attribute(claimKey, claimValues[claimKey])); } assertion.Statements.Add(samlAttrStatement); X509Certificate2 cert = GetCertificate(certThumbPrint); X509AsymmetricSecurityKey signingKey = new X509AsymmetricSecurityKey(cert); assertion.SigningCredentials = new SigningCredentials( signingKey, cert.PublicKey.Key.SignatureAlgorithm, SecurityAlgorithms.Sha1Digest, new SecurityKeyIdentifier(new X509ThumbprintKeyIdentifierClause(cert))); Saml2SecurityToken samlToken = new Saml2SecurityToken(assertion); return(samlToken); }
private static bool AreSecurityKeysEqual(SecurityKey securityKey1, SecurityKey securityKey2, CompareContext context) { if (context.IgnoreType && (securityKey1.GetType() != securityKey2.GetType())) { return(false); } // Check X509SecurityKey first so we don't have to use reflection to get cert. X509SecurityKey x509Key1 = securityKey1 as X509SecurityKey; if (x509Key1 != null) { X509SecurityKey x509Key2 = securityKey2 as X509SecurityKey; if (x509Key1.Certificate.Thumbprint == x509Key2.Certificate.Thumbprint) { return(true); } return(false); } X509AsymmetricSecurityKey x509AsymmKey1 = securityKey1 as X509AsymmetricSecurityKey; if (x509AsymmKey1 != null) { X509AsymmetricSecurityKey x509AsymmKey2 = securityKey2 as X509AsymmetricSecurityKey; X509Certificate2 x509Cert1 = TestUtilities.GetField(x509AsymmKey1, "certificate") as X509Certificate2; X509Certificate2 x509Cert2 = TestUtilities.GetField(x509AsymmKey2, "certificate") as X509Certificate2; if (x509Cert1 == null && x509Cert2 == null) { return(true); } if (x509Cert1 == null || x509Cert2 == null) { return(false); } if (x509Cert1.Thumbprint != x509Cert2.Thumbprint) { return(false); } } SymmetricSecurityKey symKey1 = securityKey1 as SymmetricSecurityKey; if (symKey1 != null) { SymmetricSecurityKey symKey2 = securityKey2 as SymmetricSecurityKey; if (!AreBytesEqual(symKey1.GetSymmetricKey(), symKey2.GetSymmetricKey())) { return(false); } } RsaSecurityKey rsaKey = securityKey1 as RsaSecurityKey; if (rsaKey != null) { RSA rsa1 = (rsaKey.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, false)) as RSA; RSA rsa2 = ((securityKey2 as RsaSecurityKey).GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, false)) as RSA; if (!string.Equals(rsa1.ToXmlString(false), rsa2.ToXmlString(false), StringComparison.Ordinal)) { return(false); } } return(true); }
[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); }
// 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); }
// huh? //[ExpectedException (typeof (ArgumentNullException))] public void IsSupportedAlgorithmNullAlgName() { X509AsymmetricSecurityKey key = new X509AsymmetricSecurityKey(cert); Assert.IsFalse(key.IsSupportedAlgorithm(null)); }