public static X509Certificate2 GetCertificate(StoreName storeName, StoreLocation storeLocation, string subjectName) { X509Store store = new X509Store(storeName, storeLocation); X509Certificate2Collection certificates = null; store.Open(OpenFlags.ReadOnly); try { X509Certificate2 result = null; // // Every time we call store.Certificates property, a new collection will be returned. // certificates = store.Certificates; for (int i = 0; i < certificates.Count; i++) { X509Certificate2 cert = certificates[i]; if (cert.SubjectName.Name.ToLower() == subjectName.ToLower()) { if (result != null) throw new ApplicationException(string.Format("There are multiple certificate for subject Name {0}", subjectName)); result = new X509Certificate2(cert); } } if (result == null) { throw new ApplicationException(string.Format("No certificate was found for subject Name {0}", subjectName)); } return result; } finally { if (certificates != null) { for (int i = 0; i < certificates.Count; i++) { X509Certificate2 cert = certificates[i]; cert.Reset(); } } store.Close(); } }
private static void ValidateCertificate(X509Certificate2 certificate, StoreName storeName, StoreLocation storeLocation) { Assert.True(certificate != null, "Certificate is null"); DateTime now = DateTime.Now; Assert.True(now > certificate.NotBefore, String.Format("The current date {{0}} is earlier than NotBefore ({1})", now, certificate.NotBefore)); Assert.True(now < certificate.NotAfter, String.Format("The current date {{0}} is later than NotAfter ({1})", now, certificate.NotAfter)); using (X509Store store = new X509Store(storeName, storeLocation)) { store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindByThumbprint, certificate.Thumbprint, validOnly: true); Assert.True(certificates.Count == 1, String.Format("Did not find valid certificate with thumbprint {0} in StoreName '{1}', StoreLocation '{2}'", certificate.Thumbprint, storeName, storeLocation)); } using (X509Store store = new X509Store(StoreName.Disallowed, storeLocation)) { store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindByThumbprint, certificate.Thumbprint, validOnly: false); Assert.True(certificates.Count == 0, "Certificate was found in Disallowed store."); } }
public static X509Certificate2 Load(StoreName name, StoreLocation location, X509FindType type, string findValue) { if (string.IsNullOrWhiteSpace(findValue)) throw new ArgumentNullException("findValue"); var store = new X509Store(name, location); store.Open(OpenFlags.ReadOnly); try { var certificates = store.Certificates.Find(type, findValue, false); if (certificates.Count != 1) { throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "Finding certificate with [StoreName:{0}, StoreLocation:{1}, X509FindType: {2}, FindValue: {3}] matched {4} certificates. A unique match is required.", name, location, type, findValue, certificates.Count)); } return certificates[0]; } finally { store.Close(); } }
private static IEnumerable<Certificate> GetCertificates(StoreName StoreName, string StoreDescription) { var store = new X509Store(StoreName, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); try { foreach (var certificate in store.Certificates) { yield return new Certificate() { Store = StoreDescription, SubjectName = certificate.SubjectName.Name, Thumbprint = certificate.Thumbprint, FriendlyName = certificate.FriendlyName, DnsName = certificate.GetNameInfo(X509NameType.DnsName, false), Version = certificate.Version, SignatureAlgorithm = certificate.SignatureAlgorithm.FriendlyName, Issuer = certificate.IssuerName.Name, NotAfter = certificate.NotAfter, NotBefore = certificate.NotBefore, HasPrivateKey = certificate.HasPrivateKey }; } } finally { store.Close(); } }
private static X509Certificate2 FindCertificate(string name) { var stores = new StoreName[] { StoreName.Root, StoreName.AuthRoot, StoreName.CertificateAuthority, StoreName.My }; foreach (StoreName storeName in stores) { using (var store = new X509Store(storeName, StoreLocation.LocalMachine)) { try { store.Open(OpenFlags.OpenExistingOnly); } catch(CryptographicException) { // Not all stores may be present continue; } try { var collection = store.Certificates.Cast<X509Certificate2>(); var cert = collection.FirstOrDefault(c => c.FriendlyName.EqualsIgnoreCase(name)); if (cert == null) { cert = collection.FirstOrDefault(c => c.Subject.EqualsIgnoreCase(name)); if (cert != null) { return cert; } } } finally { store.Close(); } } } return null; }
// Adds the given certificate to the given store unless it is // already present. Returns 'true' if the certificate was added. private static bool AddToStoreIfNeeded(StoreName storeName, StoreLocation storeLocation, X509Certificate2 certificate) { X509Store store = null; X509Certificate2 existingCert = null; try { store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadWrite); existingCert = CertificateFromThumbprint(store, certificate.Thumbprint); if (existingCert == null) { store.Add(certificate); Console.WriteLine("Added to store '{0}', location '{1}', certificate '{2}'", storeName, storeLocation, certificate.SubjectName.Name); } } finally { if (store != null) { store.Close(); } } return existingCert == null; }
/// <summary> /// Create a new resolver that is backed by the specified X509Store. Key Identifiers /// are expected to be thumbprints of X509 certificates in the store. /// </summary> public CertificateStoreKeyResolver( StoreName storeName, StoreLocation storeLocation ) { _store = new X509Store( storeName, storeLocation ); // The store is held open throughout the lifetime of the resolver _store.Open( OpenFlags.ReadOnly ); }
public static X509Certificate2 FindCertificateBy(string thumbprint, StoreName storeName, StoreLocation storeLocation, PhysicalServer server, DeploymentResult result) { if (string.IsNullOrEmpty(thumbprint)) return null; var certstore = new X509Store(storeName, storeLocation); try { certstore.Open(OpenFlags.ReadOnly); thumbprint = thumbprint.Trim(); thumbprint = thumbprint.Replace(" ", ""); foreach (var cert in certstore.Certificates) { if (string.Equals(cert.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase) || string.Equals(cert.Thumbprint, thumbprint, StringComparison.InvariantCultureIgnoreCase)) { return cert; } } result.AddError("Could not find a certificate with thumbprint '{0}' on '{1}'".FormatWith(thumbprint, server.Name)); return null; } finally { certstore.Close(); } }
public void SetCertificate(StoreLocation storeLocation, StoreName storeName, X509FindType findType, object findValue) { if (findValue == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("findValue"); } ThrowIfImmutable(); var dotNetCertificate = SecurityUtils.GetCertificateFromStore(storeName, storeLocation, findType, findValue, null); IReadOnlyList<Certificate> uwpCertificates; try { uwpCertificates = GetCertificatesFromWinRTStore(dotNetCertificate); } catch (Exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(SecurityUtils.CreateCertificateLoadException( storeName, storeLocation, findType, findValue, null, 0)); } if (uwpCertificates.Count != 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(SecurityUtils.CreateCertificateLoadException( storeName, storeLocation, findType, findValue, null, uwpCertificates.Count)); } AttachUwpCertificate(dotNetCertificate, uwpCertificates[0]); _certificate = dotNetCertificate; }
internal static bool TryResolveCertificate(StoreName storeName, StoreLocation storeLocation, X509FindType findType, object findValue, out X509Certificate2 certificate) { X509Store store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly); certificate = null; X509Certificate2Collection certs = null; X509Certificate2Collection matches = null; try { certs = store.Certificates; matches = certs.Find(findType, findValue, false); // Throwing InvalidOperationException here, following WCF precedent. // Might be worth introducing a more specific exception here. if (matches.Count == 1) { certificate = new X509Certificate2(matches[0]); return true; } } finally { CryptoHelper.ResetAllCertificates(matches); CryptoHelper.ResetAllCertificates(certs); store.Close(); } return false; }
public static X509Certificate2 ByThumbPrint(StoreName name, StoreLocation location, string thumbprint) { var store = new X509Store(name, location); X509Certificate2Collection certificates = null; store.Open(OpenFlags.ReadOnly); try { certificates = store.Certificates; var result = (from X509Certificate2 cert in certificates where cert.SubjectName.Name != null where cert.Thumbprint != null && cert.Thumbprint.Equals(thumbprint, StringComparison.OrdinalIgnoreCase) select cert) .Select(cert => new X509Certificate2(cert)) .FirstOrDefault(); if (result == null) { throw new CryptographicException(string.Format(CultureInfo.CurrentUICulture, "No certificate was found for thumbprint {0}", thumbprint)); } return result; } finally { if (certificates != null) { foreach (var cert in certificates) cert.Reset(); } store.Close(); } }
/// <summary> /// Adds a certificate to a cert store in the local machine. /// </summary> /// <param name="certificate">The file path to find the certificate file.</param> /// <param name="storeName">Name of the certificate store.</param> /// <param name="storeLocation">Location of the certificate store.</param> public static void AddCertificate(X509Certificate2 certificate, StoreName storeName, StoreLocation storeLocation) { X509Store store = null; try { store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly | OpenFlags.ReadWrite); var certificates = from cert in store.Certificates.OfType<X509Certificate2>() where cert.Thumbprint == certificate.Thumbprint select cert; if (certificates.FirstOrDefault() == null) { store.Add(certificate); Console.WriteLine(string.Format("Added certificate with thumbprint {0} to store '{1}', has private key: {2}.", certificate.Thumbprint, storeName.ToString(), certificate.HasPrivateKey)); store.Close(); store = null; } } catch (Exception ex) { throw new Exception(String.Format("AddCert exception storeName={0} storeLocation={1}", storeName.ToString(), storeLocation.ToString()), ex); } finally { if (store != null) { store.Close(); } } }
public static X509Certificate2 CertificateFromFriendlyName(StoreName name, StoreLocation location, string friendlyName) { X509Store store = null; try { store = new X509Store(name, location); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection foundCertificates = store.Certificates.Find(X509FindType.FindByIssuerName, "DO_NOT_TRUST_WcfBridgeRootCA", false); foreach (X509Certificate2 cert in foundCertificates) { if (cert.FriendlyName == friendlyName) { return cert; } } return null; } finally { if (store != null) { store.Close(); } } }
public X509SecurityTokenProvider(StoreLocation storeLocation, StoreName storeName, X509FindType findType, object findValue) { if (findValue == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("findValue"); } X509CertificateStore store = new X509CertificateStore(storeName, storeLocation); X509Certificate2Collection certificates = null; try { store.Open(OpenFlags.ReadOnly); certificates = store.Find(findType, findValue, false); if (certificates.Count < 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.CannotFindCert, storeName, storeLocation, findType, findValue))); } if (certificates.Count > 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.FoundMultipleCerts, storeName, storeLocation, findType, findValue))); } this.certificate = new X509Certificate2(certificates[0]); } finally { SecurityUtils.ResetAllCertificates(certificates); store.Close(); } }
protected virtual X509Store GetStore(StoreName storeName, StoreLocation? storeLocation = null) { if (!storeLocation.HasValue) return new X509Store(storeName); return new X509Store(storeName, storeLocation.GetValueOrDefault()); }
/// <summary> /// Private Utility method to get a certificate from a given store /// </summary> /// <param name="storeName">Name of certificate store (e.g. My, TrustedPeople)</param> /// <param name="storeLocation">Location of certificate store (e.g. LocalMachine, CurrentUser)</param> /// <param name="subjectDistinguishedName">The Subject Distinguished Name of the certificate</param> /// <returns>The specified X509 certificate</returns> static X509Certificate2 LookupCertificate( StoreName storeName, StoreLocation storeLocation, string subjectDistinguishedName ) { X509Store store = null; X509Certificate2Collection certs = null; X509Certificate2 certificate = null; try { store = new X509Store( storeName, storeLocation ); store.Open( OpenFlags.ReadOnly ); certs = store.Certificates.Find( X509FindType.FindBySubjectDistinguishedName, subjectDistinguishedName, false ); if ( certs.Count != 1 ) { throw new X509HelperException( String.Format( "FedUtil: Certificate {0} not found or more than one certificate found", subjectDistinguishedName ) ); } certificate = new X509Certificate2( certs[0] ); return certificate; } finally { if ( certs != null ) { for ( int i = 0; i < certs.Count; ++i ) { certs[i].Reset(); } } if ( store != null ) store.Close(); } }
/// <summary> /// Searches the certificate store of the current user and returns the matching certificate. /// </summary> /// <param name="thumbprint">Thumbprint of the certificate</param> /// <param name="storeName">Name of the certificate store</param> /// <param name="storeLocation">Location of the certificate store</param> /// <returns>The matching certificate</returns> public static X509Certificate2 GetCertificate(string thumbprint, StoreName storeName, StoreLocation storeLocation) { Logger.Instance.WriteMethodEntry(EventIdentifier.ProtectedDataGetCertificate, "Thumbprint: {0}.", thumbprint); try { if (string.IsNullOrEmpty(thumbprint)) { throw new ArgumentNullException("thumbprint"); } X509Store store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly); X509Certificate2 certificate = store.Certificates.Cast<X509Certificate2>().FirstOrDefault(cert => cert.Thumbprint.Equals(thumbprint, StringComparison.OrdinalIgnoreCase)); if (certificate == null) { Logger.Instance.ReportError(new Exceptions.CryptographicException(Messages.ProtectedData_EncryptionCertificateNotFoundError, thumbprint)); } return certificate; } finally { Logger.Instance.WriteMethodExit(EventIdentifier.ProtectedDataGetCertificate, "Thumbprint: {0}.", thumbprint); } }
public static X509Certificate2 GetCertificate(StoreName storeName, StoreLocation storeLocation, string thumbprint) { var certificateStore = new X509Store(storeName, storeLocation); try { certificateStore.Open(OpenFlags.ReadOnly); var certificates = certificateStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); if (certificates.Count == 1) { return certificates[0]; } if (certificates.Count > 1) { const string format = "{0} matching the thumbprint {1} were found."; var message = String.Format(format, certificates.Count, thumbprint); throw new InvalidOperationException(message); } } finally { certificateStore.Close(); } return null; }
public static X509Certificate2Collection GetCertificates(StoreName name, StoreLocation location) { X509Store store = null; try { store = new X509Store(name, location); X509Certificate2Collection certificates = null; store.Open(OpenFlags.ReadOnly); // Every time we call store.Certificates property, a new collection will be returned. return store.Certificates; } finally { if (store != null) { store.Close(); } } return null; }
// Adds the given certificate to the given store unless it is // already present. Returns 'true' if the certificate was added. private static bool AddToStoreIfNeeded(StoreName storeName, StoreLocation storeLocation, X509Certificate2 certificate) { X509Store store = null; X509Certificate2 existingCert = null; try { store = new X509Store(storeName, storeLocation); // We assume Bridge is running elevated store.Open(OpenFlags.ReadWrite); existingCert = CertificateFromThumbprint(store, certificate.Thumbprint); if (existingCert == null) { store.Add(certificate); Trace.WriteLine(string.Format("[CertificateManager] Added certificate to store: ")); Trace.WriteLine(string.Format(" {0} = {1}", "StoreName", storeName)); Trace.WriteLine(string.Format(" {0} = {1}", "StoreLocation", storeLocation)); Trace.WriteLine(string.Format(" {0} = {1}", "CN", certificate.SubjectName.Name)); Trace.WriteLine(string.Format(" {0} = {1}", "HasPrivateKey", certificate.HasPrivateKey)); Trace.WriteLine(string.Format(" {0} = {1}", "Thumbprint", certificate.Thumbprint)); } } finally { if (store != null) { store.Close(); } } return existingCert == null; }
/// <summary> /// Find a certificate with the given common name. This is an imprecise search method, as multiple certificates may have the same name. /// Returns the first certificate found matching the specified name. /// </summary> /// <param name="storeLocation">The CertificateStore to search. Some stores require admin access</param> /// <param name="storeName">The StoreName to search under. Generally "My" is the correct one to use</param> /// <param name="requirePrivateKey">Only return certificates with a PrivateKey embedded</param> /// <returns></returns> public static X509Certificate2 GetCertificateByCommonName(string commonName, StoreLocation storeLocation = StoreLocation.LocalMachine, StoreName storeName = StoreName.My, bool requirePrivateKey = false) { if (string.IsNullOrEmpty(commonName)) { throw new ArgumentNullException("commonName"); } //commonName = commonName.Replace(" ", "").ToUpperInvariant(); X509Store store = new X509Store(storeName, storeLocation); try { store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly); X509Certificate2Collection foundCerts = store.Certificates.Find(X509FindType.FindBySubjectName, commonName, false); foreach (var cert in foundCerts) { if (!requirePrivateKey || cert.HasPrivateKey) { return cert; } } } finally { store.Close(); } return null; }
/// <summary> /// Checks for the certificate in the certificate store. Loads it from a resource if it does not exist. /// </summary> public static X509Certificate2 InitializeCertificate(StoreName storeName, StoreLocation storeLocation, string subjectName) { // find matching certificate. X509Certificate2 certificate = Find(storeName, storeLocation, subjectName); // put a copy in the trusted people store because that is the default location used by WCF to determine trust. X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); try { X509Certificate2Collection hits = store.Certificates.Find(X509FindType.FindByThumbprint, certificate.Thumbprint, false); if (hits.Count == 0) { // copy the certificate to ensure the private key is not placed in the trusted people store. store.Add(new X509Certificate2(certificate.GetRawCertData())); } } finally { store.Close(); } return certificate; }
/// <summary> /// Finds the cert having thumbprint supplied from store location supplied /// </summary> /// <param name="storeName"></param> /// <param name="storeLocation"></param> /// <param name="thumbprint"></param> /// <param name="validationRequired"></param> /// <returns>X509Certificate2</returns> public static X509Certificate2 FindCertificateByThumbprint(StoreName storeName, StoreLocation storeLocation, string thumbprint, bool validationRequired) { Guard.ArgumentNotNullOrWhiteSpace(thumbprint, nameof(thumbprint)); var store = new X509Store(storeName, storeLocation); try { store.Open(OpenFlags.ReadOnly); var col = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validationRequired); if (col == null || col.Count == 0) { throw new ArgumentException("certificate was not found in store"); } return col[0]; } finally { #if NET451 // IDisposable not implemented in NET451 store.Close(); #else // Close is private in DNXCORE, but Dispose calls close internally store.Dispose(); #endif } }
/// <summary> /// Checks for the certificate in the certificate store. Loads it from a resource if it does not exist. /// </summary> public static X509Certificate2 Find(StoreName storeName, StoreLocation storeLocation, string subjectName) { X509Certificate2 certificate = null; // look for the the private key in the personal store. X509Store store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadWrite); try { X509Certificate2Collection hits = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, false); if (hits.Count == 0) { return null; } certificate = hits[0]; } finally { store.Close(); } return certificate; }
private void UninstallCertificate(StoreName storeName, StoreLocation storeLocation) { Trace.TraceInformation("Removing store object for '{1}', '{0}'.", storeName, storeLocation); var store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadWrite); try { X509Certificate2Collection result = store.Certificates.Find( X509FindType.FindByThumbprint, _cert.Thumbprint, false); if (result.Count > 0) { store.Remove(_cert); Trace.TraceInformation("Certificate successfully removed from the store."); } else { Trace.TraceWarning("Certificate with thumbprint '{0}', name '{1}' not found in store.", _cert.Thumbprint, _cert.Subject); } } finally { store.Close(); } }
public X509Store (StoreName storeName, StoreLocation storeLocation) { if (storeLocation != StoreLocation.CurrentUser && storeLocation != StoreLocation.LocalMachine) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.Arg_EnumIllegalVal), "storeLocation")); switch (storeName) { case StoreName.AddressBook: m_storeName = "AddressBook"; break; case StoreName.AuthRoot: m_storeName = "AuthRoot"; break; case StoreName.CertificateAuthority: m_storeName = "CA"; break; case StoreName.Disallowed: m_storeName = "Disallowed"; break; case StoreName.My: m_storeName = "My"; break; case StoreName.Root: m_storeName = "Root"; break; case StoreName.TrustedPeople: m_storeName = "TrustedPeople"; break; case StoreName.TrustedPublisher: m_storeName = "TrustedPublisher"; break; default: throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.Arg_EnumIllegalVal), "storeName")); } m_location = storeLocation; }
private static X509Certificate2 GetACertificateWithPrivateKeyInStore(StoreName storeName, StoreLocation storeLocation) { Trace.WriteLine(string.Format("Looking for certificates in store : {0}, store location : {1}", storeName, storeLocation)); var certificateStore = new X509Store(storeName, storeLocation); certificateStore.Open(OpenFlags.ReadOnly); foreach (var certificate in certificateStore.Certificates) { if (certificate.HasPrivateKey && certificate.PublicKey.Key.KeySize == 2048) { try { var key = certificate.PrivateKey; Trace.WriteLine("Found a suitable certificate with a private key"); Trace.WriteLine(string.Format("Certificate issuer : {0}, Subject Name : {1}", certificate.Issuer, certificate.Subject)); return certificate; } catch (Exception) { Trace.WriteLine("Ignoring a Cryptography Next generation (CNG) cert"); } } } return null; }
public X509Certificate2 GetBySerialNumber(string serialNumber, StoreLocation storeLocation, StoreName storeName) { X509Store store = new X509Store(storeName, storeLocation); var matchingCertificates = this.findAllCertificatesInStore(store, (s) => { return s.Certificates.Find(X509FindType.FindBySerialNumber, serialNumber, true); }); return this.getSingleCertificate(matchingCertificates); }
public SecurityBehavior(ServiceSecurity mode,StoreLocation storeLocation,StoreName storeName,X509FindType findType,string subjectName) { m_Mode = mode; m_StoreLocation = storeLocation; m_StoreName = storeName; m_FindType = findType; m_SubjectName = subjectName; }
/// <summary> /// 尝试获取计算机中的证书 /// </summary> public static X509Certificate2 TryGetCertificate(StoreName sn, byte[] certificatefile) { var store = new X509Store(sn, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); var certs = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, GetCertificateFromResource(certificatefile).Subject, false); store.Close(); return (certs.Count > 0) ? certs[0] : null; }
public virtual IEnumerable <NuGetCertificate> GetCertificatesByPurpose(string purpose, StoreName name, StoreLocation location) { return(GetAllCertificates(name, location) .Where(c => String.Equals(c.Purpose, purpose, StringComparison.OrdinalIgnoreCase))); }
public virtual NuGetCertificate GetCertificateFromConfigSetting(string setting, StoreName name, StoreLocation location) { if (_config == null) { return(null); } string thumbprint = _config.GetSetting(setting); if (String.IsNullOrEmpty(thumbprint)) { return(null); } var store = new X509Store(name, location); store.Open(OpenFlags.ReadOnly); var cert = store.Certificates .Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false) .Cast <X509Certificate2>() .FirstOrDefault(); return(cert == null ? null : NuGetCertificate.Create(cert)); }
/// <summary> /// Returns a SharePoint ClientContext using Azure Active Directory App Only Authentication. This requires that you have a certificated created, and updated the key credentials key in the application manifest in the azure AD accordingly. /// </summary> /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param> /// <param name="clientId">The Azure AD Application Client ID</param> /// <param name="tenant">The Azure AD Tenant, e.g. mycompany.onmicrosoft.com</param> /// <param name="storeName">The name of the store for the certificate</param> /// <param name="storeLocation">The location of the store for the certificate</param> /// <param name="thumbPrint">The thumbprint of the certificate to locate in the store</param> /// <param name="environment">SharePoint environment being used</param> /// <returns>ClientContext being used</returns> public ClientContext GetAzureADAppOnlyAuthenticatedContext(string siteUrl, string clientId, string tenant, StoreName storeName, StoreLocation storeLocation, string thumbPrint, AzureEnvironment environment = AzureEnvironment.Production) { var cert = Utilities.X509CertificateUtility.LoadCertificate(storeName, storeLocation, thumbPrint); return(GetAzureADAppOnlyAuthenticatedContext(siteUrl, clientId, tenant, cert, environment)); }
public Int32 ReadInt32 <T>(string name, params object[] idx) where T : IId { return(ReadEntry <Int32>(StoreName.ToEnum <T>(), name, idx)); }
/// <summary> /// Retrieves a certificate from the certificate store. /// </summary> /// <param name="location">The location.</param> /// <param name="name">The name.</param> /// <param name="findType">Type of the find.</param> /// <param name="value">The value.</param> /// <returns>A X509Certificate2</returns> public static X509Certificate2 GetCertificateFromStore(StoreLocation location, StoreName name, X509FindType findType, object value) { X509Store store = new X509Store(name, location); try { store.Open(OpenFlags.ReadOnly); // work around possible bug in framework if (findType == X509FindType.FindByThumbprint) { var thumbprint = value.ToString(); thumbprint = thumbprint.Trim(); thumbprint = thumbprint.Replace(" ", ""); foreach (var cert in store.Certificates) { if (string.Equals(cert.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase) || string.Equals(cert.Thumbprint, thumbprint, StringComparison.InvariantCultureIgnoreCase)) { return(cert); } } } if (findType == X509FindType.FindBySerialNumber) { var serial = value.ToString(); serial = serial.Trim(); serial = serial.Replace(" ", ""); foreach (var cert in store.Certificates) { if (string.Equals(cert.SerialNumber, serial, StringComparison.OrdinalIgnoreCase) || string.Equals(cert.SerialNumber, serial, StringComparison.InvariantCultureIgnoreCase)) { return(cert); } } } var certs = store.Certificates.Find(findType, value, false); if (certs.Count != 1) { throw new InvalidOperationException(String.Format("Certificate not found: {0}", value)); } return(certs[0]); } finally { store.Close(); } }
public static void BindCertificate(IPEndPoint ipPort, byte[] hash, StoreName storeName, Guid appId) { if (ipPort == null) { throw new ArgumentNullException("ipPort"); } if (hash == null) { throw new ArgumentNullException("hash"); } CallHttpApi( delegate { HTTP_SERVICE_CONFIG_SSL_SET configSslSet = new HTTP_SERVICE_CONFIG_SSL_SET(); GCHandle sockAddrHandle = CreateSockaddrStructure(ipPort); IntPtr pIpPort = sockAddrHandle.AddrOfPinnedObject(); HTTP_SERVICE_CONFIG_SSL_KEY httpServiceConfigSslKey = new HTTP_SERVICE_CONFIG_SSL_KEY(pIpPort); HTTP_SERVICE_CONFIG_SSL_PARAM configSslParam = new HTTP_SERVICE_CONFIG_SSL_PARAM(); GCHandle handleHash = GCHandle.Alloc(hash, GCHandleType.Pinned); configSslParam.AppId = appId; configSslParam.DefaultCertCheckMode = 0; configSslParam.DefaultFlags = 0; //HTTP_SERVICE_CONFIG_SSL_FLAG_NEGOTIATE_CLIENT_CERT; configSslParam.DefaultRevocationFreshnessTime = 0; configSslParam.DefaultRevocationUrlRetrievalTimeout = 0; configSslParam.pSslCertStoreName = storeName.ToString(); configSslParam.pSslHash = handleHash.AddrOfPinnedObject(); configSslParam.SslHashLength = hash.Length; configSslSet.ParamDesc = configSslParam; configSslSet.KeyDesc = httpServiceConfigSslKey; IntPtr pInputConfigInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_SSL_SET))); Marshal.StructureToPtr(configSslSet, pInputConfigInfo, false); try { uint retVal = HttpSetServiceConfiguration(IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, pInputConfigInfo, Marshal.SizeOf(configSslSet), IntPtr.Zero); if (ERROR_ALREADY_EXISTS != retVal) { ThrowWin32ExceptionIfError(retVal); } else { retVal = HttpDeleteServiceConfiguration(IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, pInputConfigInfo, Marshal.SizeOf(configSslSet), IntPtr.Zero); ThrowWin32ExceptionIfError(retVal); retVal = HttpSetServiceConfiguration(IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, pInputConfigInfo, Marshal.SizeOf(configSslSet), IntPtr.Zero); ThrowWin32ExceptionIfError(retVal); } } finally { Marshal.FreeCoTaskMem(pInputConfigInfo); if (handleHash.IsAllocated) { handleHash.Free(); } if (sockAddrHandle.IsAllocated) { sockAddrHandle.Free(); } } }); }
/// <summary> /// Creates an instance of Certificate where the certificate is a binary resource /// </summary> /// <param name="id">The identifier.</param> /// <param name="feature">The feature.</param> /// <param name="name">The name.</param> /// <param name="storeLocation">The store location.</param> /// <param name="storeName">Name of the store.</param> /// <param name="binaryKey">The binary key.</param> public Certificate(Id id, Feature feature, string name, StoreLocation storeLocation, StoreName storeName, string binaryKey) : this(name, storeLocation, storeName, binaryKey) { Id = id; Feature = feature; }
public static IEnumerable <X509Certificate2> FindCertificate(string search) { if (search.StartsWith("store://")) // search in the store { // store://location/name/subject // default for location is "currentuser" // allowed is "cu", "lm" as shortcut // name default is "My" search = search.Substring(8); var parts = search.Split('/'); StoreLocation storeLocation = StoreLocation.CurrentUser; StoreName storeName = StoreName.My; var filter = new string[0]; var ofs = 0; if (parts.Length >= 3) { // first should be user if (String.Compare(parts[0], "lm", StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(parts[0], "LocalMachine", StringComparison.OrdinalIgnoreCase) == 0) { storeLocation = StoreLocation.LocalMachine; } ofs++; } if (parts.Length >= 2) { if (!Enum.TryParse <StoreName>(parts[ofs], true, out storeName)) { storeName = StoreName.My; } ofs++; } if (parts.Length >= 1) { filter = parts[ofs].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); for (var i = 0; i < filter.Length; i++) { filter[i] = filter[i].Trim(); } } using (var store = new X509Store(storeName, storeLocation)) { store.Open(OpenFlags.ReadOnly); try { foreach (var c in store.Certificates) { if (filter.Length == 0 || CertifacteMatchSubject(c, filter)) { yield return(c); } } } finally { store.Close(); } } } else if (Path.IsPathRooted(search)) { yield return(new X509Certificate2(search)); } } // func FindCertificate
X509Certificate2 GetCertificate(StoreLocation storeLocation, StoreName storeName, X509FindType findType, object findValue) { return(ConfigUtil.CreateCertificateFrom(storeLocation, storeName, findType, findValue)); }
public IList <X509Certificate2> ListCertificates( StoreName storeName, StoreLocation location, bool isValid, bool requireExportable = true) { Log.ListCertificatesStart(location, storeName); var certificates = new List <X509Certificate2>(); try { using var store = new X509Store(storeName, location); store.Open(OpenFlags.ReadOnly); certificates.AddRange(store.Certificates.OfType <X509Certificate2>()); IEnumerable <X509Certificate2> matchingCertificates = certificates; matchingCertificates = matchingCertificates .Where(c => HasOid(c, AspNetHttpsOid)); if (Log.IsEnabled()) { Log.DescribeFoundCertificates(ToCertificateDescription(matchingCertificates)); } if (isValid) { // Ensure the certificate hasn't expired, has a private key and its exportable // (for container/unix scenarios). Log.CheckCertificatesValidity(); var now = DateTimeOffset.Now; var validCertificates = matchingCertificates .Where(c => IsValidCertificate(c, now, requireExportable)) .OrderByDescending(c => GetCertificateVersion(c)) .ToArray(); if (Log.IsEnabled()) { var invalidCertificates = matchingCertificates.Except(validCertificates); Log.DescribeValidCertificates(ToCertificateDescription(validCertificates)); Log.DescribeInvalidValidCertificates(ToCertificateDescription(invalidCertificates)); } matchingCertificates = validCertificates; } // We need to enumerate the certificates early to prevent disposing issues. matchingCertificates = matchingCertificates.ToList(); var certificatesToDispose = certificates.Except(matchingCertificates); DisposeCertificates(certificatesToDispose); store.Close(); Log.ListCertificatesEnd(); return((IList <X509Certificate2>)matchingCertificates); } catch (Exception e) { if (Log.IsEnabled()) { Log.ListCertificatesError(e.ToString()); } DisposeCertificates(certificates); certificates.Clear(); return(certificates); } bool HasOid(X509Certificate2 certificate, string oid) => certificate.Extensions.OfType <X509Extension>() .Any(e => string.Equals(oid, e.Oid?.Value, StringComparison.Ordinal));
public void SaveCertificateInStoreStart(string certificate, StoreName name, StoreLocation location) => WriteEvent(20, $"Saving certificate '{certificate}' to store {location}\\{name}.");
/// <summary> /// Returns a SharePoint ClientContext using High Trust Certificate App Only Authentication /// </summary> /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param> /// <param name="clientId">The SharePoint Client ID</param> /// <param name="storeName">The name of the store for the certificate</param> /// <param name="storeLocation">The location of the store for the certificate</param> /// <param name="thumbPrint">The thumbprint of the certificate to locate in the store</param> /// <param name="certificateIssuerId">The IssuerID under which the CER counterpart of the PFX has been registered in SharePoint as a Trusted Security Token issuer</param> /// <returns>Authenticated SharePoint ClientContext</returns> public ClientContext GetHighTrustCertificateAppOnlyAuthenticatedContext(string siteUrl, string clientId, StoreName storeName, StoreLocation storeLocation, string thumbPrint, string certificateIssuerId) { // Retrieve the certificate from the Windows Certificate Store var cert = Utilities.X509CertificateUtility.LoadCertificate(storeName, storeLocation, thumbPrint); return(GetHighTrustCertificateAppOnlyAuthenticatedContext(siteUrl, clientId, cert, certificateIssuerId)); }
/// <summary> /// Try and locate a certificate matching the given <paramref name="thumbprint"/> by searching in /// the in the given <see cref="StoreName"/> and <see cref="StoreLocation"/>. /// </summary> /// <param name="thumbprint">Thumbprint of certificate to locate</param> /// <param name="location"><see cref="StoreLocation"/> in which to search for a matching certificate</param> /// <param name="name"><see cref="StoreName"/> in which to search for a matching certificate</param> /// <returns><see cref="X509Certificate2"/> with <paramref name="thumbprint"/>, or null if no matching certificate was found</returns> public static X509Certificate2 FindCertificateByThumbprint(string thumbprint, StoreLocation location, StoreName name) { // Don't validate certs, since the test root isn't installed. const bool validateCerts = false; using (var store = new X509Store(name, location)) { store.Open(OpenFlags.ReadOnly); var collection = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validateCerts); return(collection.Count == 0 ? null : collection[0]); } }
public static void BindCertificate(int port, X509Certificate2 cert, StoreName storeName, string appId) { IPEndPoint ip = new IPEndPoint(0, port); BindCertificate(ip, cert.GetCertHash(), storeName, new Guid(appId)); }
public X509Store(StoreName storeName, StoreLocation storeLocation, OpenFlags flags) : this(storeName, storeLocation) { Open(flags); }
public X509CertificatesName(StoreLocation location, StoreName name) { _location = location; _name = name; }
/// <summary> /// Creates an instance of Certificate where the certificate is requested or exists at the specified path /// </summary> /// <param name="id">The identifier.</param> /// <param name="feature">The feature.</param> /// <param name="name">The name.</param> /// <param name="storeLocation">The store location.</param> /// <param name="storeName">Name of the store.</param> /// <param name="certificatePath">The certificate path.</param> /// <param name="request">if set to <c>true</c> [request].</param> public Certificate(Id id, Feature feature, string name, StoreLocation storeLocation, StoreName storeName, string certificatePath, bool request) : this(name, storeLocation, storeName, certificatePath, request) { Id = id; Feature = feature; }
public void SaveCertificateInStoreStart(string certificate, StoreName name, StoreLocation location) => WriteEvent(20, certificate, name, location);
internal static bool TryGetCertificateFromStore(StoreName storeName, StoreLocation storeLocation, X509FindType findType, object findValue, EndpointAddress target, out X509Certificate2 certificate) { certificate = GetCertificateFromStoreCore(storeName, storeLocation, findType, findValue, target, false); return(certificate != null); }
public void ListCertificatesStart(StoreLocation location, StoreName storeName) => WriteEvent(1, location, storeName);
public UInt64 ReadUInt64 <T>(string name, params object[] idx) where T : IId { return(ReadEntry <UInt64>(StoreName.ToEnum <T>(), name, idx)); }
public CertificateBinding(string certificateThumbprint, StoreName certificateStoreName, IPEndPoint ipPort, Guid appId, BindingOptions options = null) : this(certificateThumbprint, certificateStoreName.ToString(), ipPort, appId, options) { }
public MyCertificateCredential(string subjectName, StoreLocation storeLocation, StoreName storeName) : base(subjectName, storeLocation, storeName) { }
public Byte ReadByte <T>(string name, params object[] idx) where T : IId { return(ReadEntry <Byte>(StoreName.ToEnum <T>(), name, idx)); }
public X509Store(StoreName storeName) : this(storeName, StoreLocation.CurrentUser) { }
public ICertificate LoadCertificateFromStore(string thumbprint, bool pullChain, StoreLocation storeLocation = StoreLocation.CurrentUser, StoreName storeName = StoreName.My) { using (var store = new X509Store(storeName, storeLocation)) { store.Open(OpenFlags.MaxAllowed); var certList = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, true); if (certList.Count != 1) { ExceptionHelper.ThrowException(new ArgumentOutOfRangeException(nameof(thumbprint))); } var cert = certList[0]; var chain = new X509Chain(); var chainCertificates = new X509Certificate2Collection(); if (chain.Build(cert)) { //We have a chain so we can reverse the chain (we need to send the certificates with the //root last for TLS for (int i = chain.ChainElements.Count - 1; i > -1; i--) { chainCertificates.Add(chain.ChainElements[i].Certificate); } } return(LoadCertificate(cert, chainCertificates)); } }