private static void AddHttpsBinding(Session session, string installPath, X509Certificate2 cert, string certExportPath) { using (var mgr = new ServerManager()) { session.Log("Searching for site in IIS."); var site = mgr.Sites.FirstOrDefault(s => s.Applications.Any(app => app.VirtualDirectories.Any(x => AreSameDirectory(x.PhysicalPath, installPath)))); if(site == null) { session.Log("Site not found. This could be caused by the presence of IIS Express."); throw new Exception("Could not find site. This could be caused by the presence of IIS Express."); } session.Log("Site found ({0}), checking for https bindings.", site.Name); var httpsBinding = site.Bindings.FirstOrDefault(x => x.Protocol == "https" && x.BindingInformation.StartsWith("*:443")); if (httpsBinding != null) { session.Log("Binding already present ({0}), it will not be changed.", httpsBinding.BindingInformation); session.Log("Certificate sha1 fingerprint={0};", ToHex(httpsBinding.CertificateHash)); ExportPublicKey(session, certExportPath, httpsBinding.CertificateHash, httpsBinding.CertificateStoreName); return; } session.Log("Usable https binding was not found, adding new one."); var storeName = new X509Store(StoreName.My, StoreLocation.LocalMachine).Name; site.Bindings.Add("*:443:", cert.GetCertHash(), storeName); ExportPublicKey(session, certExportPath, cert.GetCertHash(), storeName); session.Log("Certificate sha1 fingerprint={0};", ToHex(cert.GetCertHash())); mgr.CommitChanges(); session.Log("Binding added."); } }
public ClaimsIdentity ProcessClientCertificate(X509Certificate2 cert, string ipAddress) { using (var per = PersistenceFactory()) { var hash = cert.GetCertHash(); var client = per.ClientGetByCertificateHash(hash); // not found? add to pending certificates list if (client == null) { TraceSource.TraceInformation("Pending certificate:\n{0} ({1})", ByteArrayHelper.ByteArrayToString(hash), ipAddress); per.PendingCertificateAddOrUpdate(hash, ipAddress); per.Save(); } // build identity var identity = new ClaimsIdentity("ClientAuthentication"); identity.AddClaim(new Claim(CertificateHashClaimType, ByteArrayHelper.ByteArrayToString(hash), ClaimValueTypes.HexBinary, ClaimIssuer)); identity.AddClaim(new Claim(IsKnownClaimType, client == null ? "false" : "true", ClaimValueTypes.Boolean, ClaimIssuer)); // known client? // add details only if authenticated if (client != null) { identity.AddClaim(new Claim(identity.NameClaimType, client.Name, ClaimValueTypes.String, ClaimIssuer)); // nick name identity.AddClaim(new Claim(ClientIdClaimType, client.Id.ToString(), ClaimValueTypes.Integer, ClaimIssuer)); // ID identity.AddClaims(client.ClientGroups.Select(group => new Claim(identity.RoleClaimType, group.Id.ToString(), ClaimValueTypes.Integer, ClaimIssuer))); // assigned groups identity.AddClaims(client.ClientGroups.Select(group => new Claim(RoleNameClaimType, group.Name, ClaimValueTypes.String, ClaimIssuer))); // assigned groups (names - informative) } return identity; } }
public string GetX509CertificateThumbprint(ClientAssertionCertificate credential) { X509Certificate2 x509Certificate = new X509Certificate2(credential.Certificate, credential.Password); // Thumbprint should be url encoded return Base64UrlEncoder.Encode(x509Certificate.GetCertHash()); }
public X509CertificateEndpointIdentity (X509Certificate2 cert) { if (cert == null) throw new ArgumentNullException ("cert"); primary = cert; Initialize (Claim.CreateThumbprintClaim (cert.GetCertHash ())); }
static byte[] GetHash(X509Certificate2 certificate) { if (certificate == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate"); return certificate.GetCertHash(); }
internal X509CertificateEndpointIdentity(XmlDictionaryReader reader) { if (reader == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); reader.MoveToContent(); if (reader.IsEmptyElement) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.UnexpectedEmptyElementExpectingClaim, XD.AddressingDictionary.X509v3Certificate.Value, XD.AddressingDictionary.IdentityExtensionNamespace.Value))); reader.ReadStartElement(XD.XmlSignatureDictionary.X509Data, XD.XmlSignatureDictionary.Namespace); while (reader.IsStartElement(XD.XmlSignatureDictionary.X509Certificate, XD.XmlSignatureDictionary.Namespace)) { reader.MoveToContent(); X509Certificate2 certificate = new X509Certificate2(Convert.FromBase64String(reader.ReadContentAsString())); if (certificateCollection.Count == 0) { // This is the first certificate. We assume this as the primary // certificate and initialize the base class. Initialize(new Claim(ClaimTypes.Thumbprint, certificate.GetCertHash(), Rights.PossessProperty)); } certificateCollection.Add(certificate); } reader.ReadEndElement(); if (certificateCollection.Count == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.UnexpectedEmptyElementExpectingClaim, XD.AddressingDictionary.X509v3Certificate.Value, XD.AddressingDictionary.IdentityExtensionNamespace.Value))); }
public X509CertificateEndpointIdentity(X509Certificate2 certificate) { if (certificate == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate"); Initialize(new Claim(ClaimTypes.Thumbprint, certificate.GetCertHash(), Rights.PossessProperty)); certificateCollection.Add(certificate); }
private IReadOnlyList<Certificate> GetCertificatesFromWinRTStore(X509Certificate2 dotNetCertificate) { var query = new CertificateQuery { Thumbprint = dotNetCertificate.GetCertHash(), IncludeDuplicates = false }; return CertificateStores.FindAllAsync(query).AsTask().GetAwaiter().GetResult(); }
public bool Matches (X509Certificate2 certificate) { if (certificate == null) throw new ArgumentNullException ("certificate"); byte [] b1 = GetRawBuffer (); byte [] b2 = certificate.GetCertHash (); if (b1.Length != b2.Length) return false; for (int i = 0; i < b1.Length; i++) if (b1 [i] != b2 [i]) return false; return true; }
public byte[] InstallCertificateWithPrivateKey(string certificatePath, string certificateStoreName, RSAParameters privateKey) { var certificateBytes = File.ReadAllBytes(certificatePath); var x509 = new X509Certificate2(certificateBytes, (string)null, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet); var csp = new CspParameters { KeyContainerName = x509.GetCertHashString(), Flags = CspProviderFlags.UseMachineKeyStore }; var rsa = new RSACryptoServiceProvider(csp); rsa.ImportParameters(privateKey); x509.PrivateKey = rsa; Info($"Installing certificate private key to localmachine\\{certificateStoreName}, container name {csp.KeyContainerName}"); InstallCertificateToStore(x509, certificateStoreName); return x509.GetCertHash(); }
public void CreateClaims () { Claim c; // premises Assert.AreEqual ("http://schemas.xmlsoap.org/ws/2005/05/identity/right/identity", Rights.Identity, "#1"); Assert.AreEqual ("http://schemas.xmlsoap.org/ws/2005/05/identity/right/possessproperty", Rights.PossessProperty, "#2"); c = Claim.CreateDnsClaim ("123.45.6.7"); AssertClaim ("Dns", c, ClaimTypes.Dns, "123.45.6.7", Rights.PossessProperty); Uri uri = new Uri ("http://www.mono-project.com"); c = Claim.CreateUriClaim (uri); AssertClaim ("Uri", c, ClaimTypes.Uri, uri, Rights.PossessProperty); MailAddress mail = new MailAddress ("*****@*****.**"); c = Claim.CreateMailAddressClaim (mail); AssertClaim ("Mail", c, ClaimTypes.Email, mail, Rights.PossessProperty); c = Claim.CreateNameClaim ("Rupert"); AssertClaim ("Name", c, ClaimTypes.Name, "Rupert", Rights.PossessProperty); c = Claim.CreateSpnClaim ("foo"); AssertClaim ("Spn", c, ClaimTypes.Spn, "foo", Rights.PossessProperty); c = Claim.CreateUpnClaim ("foo"); AssertClaim ("Upn", c, ClaimTypes.Upn, "foo", Rights.PossessProperty); //SecurityIdentifier sid = new SecurityIdentifier (blah); //c = Claim.CreateWindowsSidClaim (sid); //AssertClaim ("Sid", c, ClaimTypes.Sid, blah, Rights.PossessProperty); byte [] hash = new byte [] {1, 2, 3, 4, 5, 6, 7, 8, 9}; c = Claim.CreateHashClaim (hash); AssertClaim ("Hash", c, ClaimTypes.Hash, hash, Rights.PossessProperty); RSA rsa = RSA.Create (); c = Claim.CreateRsaClaim (rsa); AssertClaim ("Rsa", c, ClaimTypes.Rsa, rsa, Rights.PossessProperty); X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); byte [] chash = cert.GetCertHash (); c = Claim.CreateThumbprintClaim (chash); AssertClaim ("Thumbprint", c, ClaimTypes.Thumbprint, chash, Rights.PossessProperty); c = Claim.CreateX500DistinguishedNameClaim (cert.SubjectName); AssertClaim ("X500Name", c, ClaimTypes.X500DistinguishedName, cert.SubjectName, Rights.PossessProperty); }
private static bool StoreContainsCertificate(string storeName, X509Certificate2 certificate) { var store = new X509Store(storeName, StoreLocation.LocalMachine); try { store.Open(OpenFlags.ReadOnly); var result = store.Certificates.OfType<X509Certificate2>().Any(x => x.GetCertHash() == certificate.GetCertHash()); return result; } finally { store.Close(); } }
public X509CertificateClaimSet (X509Certificate2 certificate) { if (certificate == null) throw new ArgumentNullException ("certificate"); this.cert = certificate; Claim ident = new Claim (ClaimTypes.Thumbprint, cert.Thumbprint, Rights.Identity); // issuer = new X509IdentityClaimSet (ident); claims.Add (ident); //claims.Add (Claim.CreateX500DistinguishedNameClaim (cert.SubjectName)); //claims.Add (Claim.CreateNameClaim (cert.SubjectName.Name)); RSA rsa = cert.PublicKey.Key as RSA; if (rsa != null) claims.Add (Claim.CreateRsaClaim (rsa)); claims.Add (Claim.CreateThumbprintClaim (cert.GetCertHash ())); // FIXME: where is DNS info for X509 cert? claims.Add (Claim.CreateDnsClaim (null)); }
public X509CertificateEndpointIdentity(X509Certificate2 primaryCertificate, X509Certificate2Collection supportingCertificates) { if (primaryCertificate == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("primaryCertificate"); if (supportingCertificates == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("supportingCertificates"); Initialize(new Claim(ClaimTypes.Thumbprint, primaryCertificate.GetCertHash(), Rights.PossessProperty)); certificateCollection.Add(primaryCertificate); for (int i = 0; i < supportingCertificates.Count; ++i) { certificateCollection.Add(supportingCertificates[i]); } }
private static IEnumerable<Claim> ExtractClaims(X509Certificate2 cert, string issuer) { var claims = new Collection<Claim> { new Claim(ClaimTypes.Thumbprint,Convert.ToBase64String(cert.GetCertHash()), ClaimValueTypes.Base64Binary, issuer), new Claim(ClaimTypes.X500DistinguishedName, cert.SubjectName.Name, ClaimValueTypes.String, issuer), new Claim(ClaimTypes.SerialNumber, cert.SerialNumber, ClaimValueTypes.String, issuer), new Claim(ClaimTypes.AuthenticationMethod, X509AuthnMethod, ClaimValueTypes.String, issuer) }; var email = cert.GetNameInfo(X509NameType.EmailName, false); if (email != null) { claims.Add(new Claim(ClaimTypes.Email, email, ClaimValueTypes.String, issuer)); } return claims; }
protected override void ProcessRecord() { if (!System.IO.Path.IsPathRooted(CertPath)) { CertPath = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, CertPath); } var cert = new X509Certificate2(CertPath); var rawCert = cert.GetRawCertData(); var base64Cert = Convert.ToBase64String(rawCert); var rawCertHash = cert.GetCertHash(); var base64CertHash = Convert.ToBase64String(rawCertHash); var keyId = Guid.NewGuid().ToString(); var output = string.Format("\"keyCredentials\": [\n\t{{\n\t\t\"customKeyIdentifier\": \"{0}\",\n\t\t\"keyId\": \"{1}\",\n\t\t\"type\": \"AsymmetricX509Cert\",\n\t\t\"usage\": \"Verify\",\n\t\t\"value\": \"{2}\"\n\t}}\n],", base64CertHash, keyId, base64Cert); WriteObject(output); }
public override void Install(Target target, string pfxFilename, X509Store store, X509Certificate2 certificate) { using (var iisManager = new ServerManager()) { var site = GetSite(target, iisManager); var existingBinding = (from b in site.Bindings where b.Host == target.Host && b.Protocol == "https" select b).FirstOrDefault(); if (existingBinding != null) { Console.WriteLine($" Updating Existing https Binding"); existingBinding.CertificateHash = certificate.GetCertHash(); existingBinding.CertificateStoreName = store.Name; } else { Console.WriteLine($" Adding https Binding"); var iisBinding = site.Bindings.Add(":443:" + target.Host, certificate.GetCertHash(), store.Name); iisBinding.Protocol = "https"; } Console.WriteLine($" Commiting binding changes to IIS"); iisManager.CommitChanges(); } }
/// <summary> /// Generates a self-signed assertion. /// </summary> /// <param name="webToken">Json web token.</param> /// <param name="signingCert">Signing certificate.</param> /// <returns>Self signed assertion.</returns> public static string GenerateAssertion( JsonWebToken webToken, X509Certificate2 signingCert) { string encodedHash = Base64Utils.Encode(signingCert.GetCertHash()); TokenHeader tokenHeaderContract = new TokenHeader("RS256", encodedHash); string tokenHeader = Base64Utils.Encode(tokenHeaderContract.EncodeToJson()); string tokenBody = Base64Utils.Encode(webToken.EncodeToJson()); string rawToken = string.Format("{0}.{1}", tokenHeader, tokenBody); string hash = Base64Utils.Encode(JWTTokenHelper.SignData(signingCert, rawToken)); string accessToken = string.Format( "{0}.{1}", rawToken, hash); return accessToken; }
public X509ThumbprintKeyIdentifierClause (X509Certificate2 certificate) : base (null, certificate.GetCertHash (), true) { }
/// <summary> /// Signs the token. /// </summary> /// <param name="tokenXml">The token XML.</param> /// <param name="signer">The signer.</param> /// <returns>The signed token XML</returns> protected virtual XElement SignToken(XElement tokenXml, X509Certificate2 signer) { Contract.Requires(tokenXml != null); Contract.Requires(signer != null); Contract.Ensures(Contract.Result<XElement>() != null); // create SignedXml instance and set signer key var signedXml = new SignedXml(tokenXml.ToXmlElement()); signedXml.SigningKey = signer.PrivateKey; // add an enveloped transformation to the reference. Reference reference = new Reference { Uri = "" }; reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); // add the reference to the SignedXml object. signedXml.AddReference(reference); // add a key info to the SignedXml object KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoName(Convert.ToBase64String(signer.GetCertHash()))); signedXml.KeyInfo = keyInfo; // compute the signature. signedXml.ComputeSignature(); // get the XML representation of the signature return signedXml.GetXml().ToXElement(); }
public void AddBinding(X509Certificate2 certificate, WebSite website) { using (var srvman = GetServerManager()) { // Look for dedicated ip var dedicatedIp = SiteHasBindingWithDedicatedIp(srvman, website); // Look for all the hostnames this certificate is valid for if we are using SNI var hostNames = new List<string>(); if (!dedicatedIp) { hostNames.AddRange(certificate.Extensions.Cast<X509Extension>() .Where(e => e.Oid.Value == "2.5.29.17") // Subject Alternative Names .SelectMany(e => e.Format(true).Split(new[] {"\r\n", "\n", "\n"}, StringSplitOptions.RemoveEmptyEntries).Where(s => s.Contains("=")).Select(s => s.Split('=')[1])).Where(s => !s.Contains(" "))); } var simpleName = certificate.GetNameInfo(X509NameType.SimpleName, false); if (hostNames.All(h => h != simpleName)) { hostNames.Add(simpleName); } var wildcardHostName = hostNames.SingleOrDefault(h => h.StartsWith("*.")); // If a wildcard certificate is used if (wildcardHostName != null) { if (!dedicatedIp) { // If using a wildcard ssl and not a dedicated IP, we take all the matching bindings on the site and use it to bind to SSL also. hostNames.Remove(wildcardHostName); hostNames.AddRange(website.Bindings.Where(b => !string.IsNullOrEmpty(b.Host) && b.Host.EndsWith(wildcardHostName.Substring(2))).Select(b => b.Host)); } } // For every hostname foreach (var hostName in hostNames) { var bindingIpAddress = string.IsNullOrEmpty(website.SiteInternalIPAddress) ? website.SiteIPAddress : website.SiteInternalIPAddress; var bindingInformation = string.Format("{0}:443:{1}", bindingIpAddress ?? "*", dedicatedIp ? "" : hostName); Binding siteBinding = UseCCS ? srvman.Sites[website.SiteId].Bindings.Add(bindingInformation, "https") : srvman.Sites[website.SiteId].Bindings.Add(bindingInformation, certificate.GetCertHash(), CertificateStoreName); if (UseSNI && !dedicatedIp) { siteBinding.SslFlags |= SslFlags.Sni; } if (UseCCS) { siteBinding.SslFlags |= SslFlags.CentralCertStore; } } srvman.CommitChanges(); } }
public override void Install(Target target, string pfxFilename, X509Store store, X509Certificate2 certificate) { using (var iisManager = new ServerManager()) { var site = GetSite(target, iisManager); List<string> hosts = new List<string>(); if (!Program.Options.San) { hosts.Add(target.Host); } if (target.AlternativeNames != null) { if (target.AlternativeNames.Count > 0) { hosts.AddRange(target.AlternativeNames); } } foreach (var host in hosts) { var existingBinding = (from b in site.Bindings where b.Host == host && b.Protocol == "https" select b).FirstOrDefault(); if (existingBinding != null) { if (!Program.Options.KeepExisting) { Console.WriteLine($" Removing Existing https Binding"); Log.Information("Removing Existing https Binding"); site.Bindings.Remove(existingBinding); Console.WriteLine($" Adding https Binding"); Log.Information("Adding https Binding"); var iisBinding = site.Bindings.Add(existingBinding.BindingInformation, certificate.GetCertHash(), store.Name); iisBinding.Protocol = "https"; if (_iisVersion.Major >= 8) iisBinding.SetAttributeValue("sslFlags", 1); // Enable SNI support } else { Console.WriteLine($" Updating Existing https Binding"); Log.Information("Updating Existing https Binding"); existingBinding.CertificateStoreName = store.Name; existingBinding.CertificateHash = certificate.GetCertHash(); } } else { Console.WriteLine($" Adding https Binding"); Log.Information("Adding https Binding"); var existingHTTPBinding = (from b in site.Bindings where b.Host == host && b.Protocol == "http" select b) .FirstOrDefault(); if (existingHTTPBinding != null) //This had been a fix for the multiple site San cert, now it's just a precaution against erroring out { string HTTPEndpoint = existingHTTPBinding.EndPoint.ToString(); string IP = HTTPEndpoint.Remove(HTTPEndpoint.IndexOf(':'), (HTTPEndpoint.Length - HTTPEndpoint.IndexOf(':'))); if (IP == "0.0.0.0") { IP = ""; //Remove the IP if it is 0.0.0.0 That happens if an IP wasn't set on the HTTP site and it used any available IP } var iisBinding = site.Bindings.Add(IP + ":443:" + host, certificate.GetCertHash(), store.Name); iisBinding.Protocol = "https"; if (_iisVersion.Major >= 8) iisBinding.SetAttributeValue("sslFlags", 1); // Enable SNI support } else { Log.Warning("No HTTP binding for {host} on {name}", host, site.Name); } } } Console.WriteLine($" Committing binding changes to IIS"); Log.Information("Committing binding changes to IIS"); iisManager.CommitChanges(); } }
static HttpContent GetPatchContent(JObject appObject, X509Certificate2 certificate) { var cred = new JObject(); cred["startDate"] = DateTime.UtcNow.ToString("o"); cred["endDate"] = DateTime.UtcNow.AddYears(1).ToString("o"); cred["type"] = "AsymmetricX509Cert"; cred["usage"] = "Verify"; cred["customKeyIdentifier"] = Convert.ToBase64String(certificate.GetCertHash()); cred["value"] = Convert.ToBase64String(certificate.GetRawCertData()); var creds = GetKeyCredentials(appObject); creds.Add(cred); var json = new JObject(); json["odata.type"] = "Microsoft.DirectoryServices.Application"; json["*****@*****.**"] = "Collection(Microsoft.DirectoryServices.KeyCredential)"; json["keyCredentials"] = creds; return new StringContent(json.ToString(Newtonsoft.Json.Formatting.None), Encoding.UTF8, "application/json"); }
// Filters the given list of certificates down to only the certificates that match the given certificate. private void FindMatchingCertificates(List<X509Certificate2> certificates, X509Certificate2 certificate) { byte[] hash = certificate.GetCertHash(); byte[] key = certificate.GetPublicKey(); for (int i = certificates.Count - 1; i >= 0; i--) { if (!hash.SequenceEqual(certificates[i].GetCertHash()) || !key.SequenceEqual(certificates[i].GetPublicKey())) certificates.RemoveAt(i); } }
public override void Install(Target target, string pfxFilename, X509Store store, X509Certificate2 certificate) { using (var iisManager = new ServerManager()) { var site = GetSite(target, iisManager); List<string> hosts = new List<string>(); if (!Program.Options.San) { hosts.Add(target.Host); } if (target.AlternativeNames != null) { if (target.AlternativeNames.Count > 0) { hosts.AddRange(target.AlternativeNames); } } foreach (var host in hosts) { var existingBinding = (from b in site.Bindings where b.Host == host && b.Protocol == "https" select b).FirstOrDefault(); if (existingBinding != null) { Console.WriteLine($" Updating Existing https Binding"); Log.Information("Updating Existing https Binding"); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($" IIS will serve the new certificate after the Application Pool Idle Timeout time has been reached."); Log.Information("IIS will serve the new certificate after the Application Pool Idle Timeout time has been reached."); Console.ResetColor(); existingBinding.CertificateStoreName = store.Name; existingBinding.CertificateHash = certificate.GetCertHash(); } else { Console.WriteLine($" Adding https Binding"); Log.Information("Adding https Binding"); var existingHTTPBinding = (from b in site.Bindings where b.Host == host && b.Protocol == "http" select b) .FirstOrDefault(); if (existingHTTPBinding != null) //This had been a fix for the multiple site San cert, now it's just a precaution against erroring out { string IP = GetIP(existingHTTPBinding.EndPoint.ToString(), host); var iisBinding = site.Bindings.Add(IP + ":443:" + host, certificate.GetCertHash(), store.Name); iisBinding.Protocol = "https"; if (_iisVersion.Major >= 8) iisBinding.SetAttributeValue("sslFlags", 1); // Enable SNI support } else { Log.Warning("No HTTP binding for {host} on {name}", host, site.Name); } } } Console.WriteLine($" Committing binding changes to IIS"); Log.Information("Committing binding changes to IIS"); iisManager.CommitChanges(); } }
private static SSLCertificate GetSSLCertificateFromX509Certificate2(X509Certificate2 cert) { var certificate = new SSLCertificate { Hostname = cert.GetNameInfo(X509NameType.SimpleName, false), FriendlyName = cert.FriendlyName, CSRLength = Convert.ToInt32(cert.PublicKey.Key.KeySize.ToString(CultureInfo.InvariantCulture)), Installed = true, DistinguishedName = cert.Subject, Hash = cert.GetCertHash(), SerialNumber = cert.SerialNumber, ExpiryDate = DateTime.Parse(cert.GetExpirationDateString()), ValidFrom = DateTime.Parse(cert.GetEffectiveDateString()), Success = true }; return certificate; }
/// <summary> /// Calculates the key id for a given x509 certificate /// </summary> /// <param name="certificate"></param> /// <returns>kid</returns> public Task<string> GetKidAsync(X509Certificate2 certificate) { return Task.FromResult(Base64Url.Encode(certificate.GetCertHash())); }
public static IEnumerable<Claim> GetClaimsFromCertificate(X509Certificate2 certificate, string issuer) { if (certificate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate"); } ICollection<Claim> claimsCollection = new Collection<Claim>(); string thumbprint = Convert.ToBase64String(certificate.GetCertHash()); claimsCollection.Add(new Claim(ClaimTypes.Thumbprint, thumbprint, ClaimValueTypes.Base64Binary, issuer)); string value = certificate.SubjectName.Name; if (!string.IsNullOrEmpty(value)) { claimsCollection.Add(new Claim(ClaimTypes.X500DistinguishedName, value, ClaimValueTypes.String, issuer)); } value = certificate.GetNameInfo(X509NameType.DnsName, false); if (!string.IsNullOrEmpty(value)) { claimsCollection.Add(new Claim(ClaimTypes.Dns, value, ClaimValueTypes.String, issuer)); } value = certificate.GetNameInfo(X509NameType.SimpleName, false); if (!string.IsNullOrEmpty(value)) { claimsCollection.Add(new Claim(ClaimTypes.Name, value, ClaimValueTypes.String, issuer)); } value = certificate.GetNameInfo(X509NameType.EmailName, false); if (!string.IsNullOrEmpty(value)) { claimsCollection.Add(new Claim(ClaimTypes.Email, value, ClaimValueTypes.String, issuer)); } value = certificate.GetNameInfo(X509NameType.UpnName, false); if (!string.IsNullOrEmpty(value)) { claimsCollection.Add(new Claim(ClaimTypes.Upn, value, ClaimValueTypes.String, issuer)); } value = certificate.GetNameInfo(X509NameType.UrlName, false); if (!string.IsNullOrEmpty(value)) { claimsCollection.Add(new Claim(ClaimTypes.Uri, value, ClaimValueTypes.String, issuer)); } RSA rsa = certificate.PublicKey.Key as RSA; if (rsa != null) { claimsCollection.Add(new Claim(ClaimTypes.Rsa, rsa.ToXmlString(false), ClaimValueTypes.RsaKeyValue, issuer)); } DSA dsa = certificate.PublicKey.Key as DSA; if (dsa != null) { claimsCollection.Add(new Claim(ClaimTypes.Dsa, dsa.ToXmlString(false), ClaimValueTypes.DsaKeyValue, issuer)); } value = certificate.SerialNumber; if (!string.IsNullOrEmpty(value)) { claimsCollection.Add(new Claim(ClaimTypes.SerialNumber, value, ClaimValueTypes.String, issuer)); } return claimsCollection; }
static bool StoreContainsCertificate(StoreName storeName, X509Certificate2 certificate) { X509CertificateStore store = new X509CertificateStore(storeName, StoreLocation.CurrentUser); X509Certificate2Collection certificates = null; try { store.Open(OpenFlags.ReadOnly); certificates = store.Find(X509FindType.FindByThumbprint, certificate.GetCertHash(), false); return certificates.Count > 0; } finally { SecurityUtils.ResetAllCertificates(certificates); store.Close(); } }
internal X509CertificateEndpointIdentity(XmlDictionaryReader reader) { this.certificateCollection = new X509Certificate2Collection(); if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } reader.MoveToContent(); if (reader.IsEmptyElement) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("UnexpectedEmptyElementExpectingClaim", new object[] { XD.AddressingDictionary.X509v3Certificate.Value, XD.AddressingDictionary.IdentityExtensionNamespace.Value }))); } reader.ReadStartElement(XD.XmlSignatureDictionary.X509Data, XD.XmlSignatureDictionary.Namespace); while (reader.IsStartElement(XD.XmlSignatureDictionary.X509Certificate, XD.XmlSignatureDictionary.Namespace)) { X509Certificate2 certificate = new X509Certificate2(Convert.FromBase64String(reader.ReadElementString())); if (this.certificateCollection.Count == 0) { base.Initialize(new Claim(ClaimTypes.Thumbprint, certificate.GetCertHash(), Rights.PossessProperty)); } this.certificateCollection.Add(certificate); } reader.ReadEndElement(); if (this.certificateCollection.Count == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("UnexpectedEmptyElementExpectingClaim", new object[] { XD.AddressingDictionary.X509v3Certificate.Value, XD.AddressingDictionary.IdentityExtensionNamespace.Value }))); } }