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(); } }
static X509Certificate2 GetCertificate(string certFindValue) { StoreLocation[] locations = new StoreLocation[] { StoreLocation.LocalMachine, StoreLocation.CurrentUser }; foreach (StoreLocation location in locations) { X509Store store = new X509Store(StoreName.My, location); store.Open(OpenFlags.OpenExistingOnly); X509Certificate2Collection collection = store.Certificates.Find( X509FindType.FindBySubjectName, certFindValue, false); if (collection.Count == 0) { collection = store.Certificates.Find( X509FindType.FindByThumbprint, certFindValue, false); } store.Close(); if (collection.Count > 0) { return collection[0]; } } throw new ArgumentException("No certificate can be found using the find value " + certFindValue); }
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(); } }
/// <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 } }
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); }
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 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(); } }
public X509Certificate2 GetCertificate(string thumbprint, StoreLocation storeLocation) { X509Store certStore = new X509Store(StoreName.My, storeLocation); X509Certificate2 certToUse = null; try { try { certStore.Open(OpenFlags.ReadOnly); } catch (Exception ex) { var outerEx = new Exception("Failed to open X509Store My on CurrentUser.", ex); throw outerEx; } var primaryCertificateThumbprint = thumbprint.ToLower(); var certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, primaryCertificateThumbprint, false); if (certCollection == null || certCollection.Count == 0) { return null; } certToUse = certCollection[0]; if (certToUse.Thumbprint.ToLower() != primaryCertificateThumbprint.ToLower()) { return null; } } finally { certStore.Close(); } return certToUse; }
internal static List<string> GetStoreNamesAtLocation(StoreLocation location) { NativeMethods.CertStoreFlags certStoreFlag = NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER; StoreLocation storeLocation = location; switch (storeLocation) { case StoreLocation.CurrentUser: { certStoreFlag = NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER; break; } case StoreLocation.LocalMachine: { certStoreFlag = NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; break; } } NativeMethods.CertEnumSystemStoreCallBackProto certEnumSystemStoreCallBackProto = new NativeMethods.CertEnumSystemStoreCallBackProto(Crypt32Helpers.CertEnumSystemStoreCallBack); List<string> strs = new List<string>(); lock (Crypt32Helpers.staticLock) { Crypt32Helpers.storeNames.Clear(); NativeMethods.CertEnumSystemStore(certStoreFlag, IntPtr.Zero, IntPtr.Zero, certEnumSystemStoreCallBackProto); foreach (string storeName in Crypt32Helpers.storeNames) { strs.Add(storeName); } } return strs; }
/// <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(); } } }
/// <summary> /// Gets a X509 specific certificate from windows store withoit asking the user. /// </summary> /// <returns></returns> public static X509Certificate2 GetCertificate(StoreLocation location, string subjectName) { X509Certificate2 cert = null; var store = new X509Store(StoreName.My, location); store.Open(OpenFlags.ReadOnly); try { X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, false); if (certs.Count == 1) { cert = certs[0]; } else { cert = null; } } finally { if (store != null) { store.Close(); } } return cert; }
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(); } }
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; }
/// <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(); } }
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; }
// 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; }
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 IFluentHpkpOptions PinCertificate(string thumbprint, StoreLocation storeLocation = StoreLocation.LocalMachine, StoreName storeName = StoreName.My) { try { _validator.ValidateThumbprint(thumbprint); } catch (Exception e) { throw new ArgumentException(e.Message, thumbprint); } var helper = new X509Helper(); var cert = helper.GetCertByThumbprint(thumbprint, storeLocation, storeName); var pin = helper.GetSubjectPublicKeyInfoPinValue(cert); cert.Reset(); if (!_pins.Contains(pin)) { _pins.Add(pin); } return this; }
private static X509Certificate2 GetCertificateFromStore(string thumbprint, StoreLocation location) { if (thumbprint != null) { X509Store store = null; try { store = new X509Store(StoreName.My, location); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); if (certificates.Count > 0) { return certificates[0]; } } catch { } finally { if (store != null) { 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 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 NuGetCertificate FindCert(CertificatesHub certs, StoreLocation storeLocation) { var specificMatch = certs.GetCertificateFromConfigSetting(ConfigSetting, StoreName.My, storeLocation); if(specificMatch != null) { AzureHubEventSource.Log.SingleMatch(storeLocation.ToString(), specificMatch.Thumbprint, specificMatch.Subject); return specificMatch; } var candidates = certs .GetCertificatesByPurpose(CommonCertificatePurposes.AzureManagement, StoreName.My, storeLocation) .ToList(); // No candidates? Return null. if (candidates.Count == 0) { AzureHubEventSource.Log.NoMatch(storeLocation.ToString()); return null; } // One candidate? Return it. else if (candidates.Count == 1) { AzureHubEventSource.Log.SingleMatch(storeLocation.ToString(), candidates[0].Thumbprint, candidates[0].Subject); return candidates[0]; } // Multiple candidates? Return the first one else { var match = candidates.FirstOrDefault(); AzureHubEventSource.Log.MultipleMatches(storeLocation.ToString(), match.Thumbprint, match.Subject); return match; } }
/// <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> /// 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); } }
// 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; }
internal X509ClientCertificateAuthentication() { this.certificateValidationMode = X509CertificateValidationMode.ChainTrust; this.revocationMode = X509RevocationMode.Online; this.trustedStoreLocation = StoreLocation.LocalMachine; this.includeWindowsGroups = true; }
public X509Certificate2 GetCertificateByThumbprint(StoreLocation storeLocation, string thumbprint) { X509Store certStore = new X509Store(StoreName.My, storeLocation); try { try { certStore.Open(OpenFlags.ReadOnly); } catch (Exception ex) { var outerEx = new SecurityException(string.Format("Failed to open X509Store in '{0}'.", storeLocation.ToString()), ex); throw outerEx; } foreach(var thisCert in certStore.Certificates) { Console.WriteLine(thisCert.Thumbprint + "\t" + thisCert.Subject); } var certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); if (certCollection == null || certCollection.Count == 0) { throw new ArgumentException(string.Format("thumbprint '{0}' does not match any certificates in '{1}'.", thumbprint, storeLocation.ToString())); } var cert = certCollection[0]; return cert; } finally { certStore.Close(); } }
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; }
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; }
protected virtual X509Store GetStore(StoreName storeName, StoreLocation? storeLocation = null) { if (!storeLocation.HasValue) return new X509Store(storeName); return new X509Store(storeName, storeLocation.GetValueOrDefault()); }
/// <summary> /// 非对称的Hash签名 /// </summary> /// <param name="storeName"></param> /// <param name="location"></param> /// <param name="certName">CN=myCerName...</param> public static IHash Hash(StoreName storeName, StoreLocation location, string certName) { return(new BaseCertificate(storeName, location, certName)); }
public static void FailedToOpenStore(this ILogger <HttpsConnectionMiddleware> logger, StoreLocation storeLocation, Exception exception) { var storeLocationString = storeLocation == StoreLocation.LocalMachine ? nameof(StoreLocation.LocalMachine) : nameof(StoreLocation.CurrentUser); FailedToOpenStore(logger, storeLocationString, exception); }
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); }
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."); } }
/// <summary> /// Get a certificate with the specified subject name from the predefined certificate storage /// Only valid certificates should be considered /// </summary> /// <param name="storeName"></param> /// <param name="storeLocation"></param> /// <param name="subjectName"></param> /// <returns> The requested certificate. If no valid certificate is found, returns null. </returns> public static X509Certificate2 GetCertificateFromStorage(StoreName storeName, StoreLocation storeLocation, string subjectName) { X509Store store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certCollection = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, true); /// Check whether the subjectName of the certificate is exactly the same as the given "subjectName" foreach (X509Certificate2 c in certCollection) { if (c.SubjectName.Name.StartsWith(string.Format("CN={0}", subjectName))) { return(c); } } return(null); }
public void SetCertificate( string subjectName, StoreLocation storeLocation, StoreName storeName) { certificate = ConfigUtil.CreateCertificateFrom(storeLocation, storeName, X509FindType.FindBySubjectName, subjectName); }
public void SetCertificate(StoreLocation storeLocation, StoreName storeName, X509FindType findType, object findValue) { certificate = ConfigUtil.CreateCertificateFrom(storeLocation, storeName, findType, findValue); }
/// <summary> /// Loads a certificate from the certificate store. /// </summary> /// <remarks> /// Exact subject match is loaded if present, otherwise best matching certificate with the subject name that contains supplied subject. /// Subject comparison is case-insensitive. /// </remarks> /// <param name="subject">The certificate subject.</param> /// <param name="storeName">The certificate store name.</param> /// <param name="storeLocation">The certificate store location.</param> /// <param name="allowInvalid">Whether or not to load certificates that are considered invalid.</param> /// <returns>The loaded certificate.</returns> public static X509Certificate2 LoadFromStoreCert(string subject, string storeName, StoreLocation storeLocation, bool allowInvalid) { using (var store = new X509Store(storeName, storeLocation)) { X509Certificate2Collection?storeCertificates = null; X509Certificate2? foundCertificate = null; try { store.Open(OpenFlags.ReadOnly); storeCertificates = store.Certificates; foreach (var certificate in storeCertificates.Find(X509FindType.FindBySubjectName, subject, !allowInvalid) .OfType <X509Certificate2>() .Where(IsCertificateAllowedForServerAuth) .Where(DoesCertificateHaveAnAccessiblePrivateKey) .OrderByDescending(certificate => certificate.NotAfter)) { // Pick the first one if there's no exact match as a fallback to substring default. foundCertificate ??= certificate; if (certificate.GetNameInfo(X509NameType.SimpleName, true).Equals(subject, StringComparison.InvariantCultureIgnoreCase)) { foundCertificate = certificate; break; } } if (foundCertificate == null) { throw new InvalidOperationException(CoreStrings.FormatCertNotFoundInStore(subject, storeLocation, storeName, allowInvalid)); } return(foundCertificate); } finally { DisposeCertificates(storeCertificates, except: foundCertificate); } } }
public static X509Certificate2 GetTlsCertificate(string thumbprint, StoreName storeName, StoreLocation storeLocation) { X509Store store = null; try { store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certCollection = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); return(certCollection.Count == 0 ? null : certCollection[0]); } finally { if (store != null) { store.Close(); } } }
/// <summary> /// Start all IMAP proxy instances from the specified settings file. /// </summary> /// <param name="fileName">File containing the IMAP proxy settings.</param> public static List <ImapProxy> StartProxiesFromSettingsFile(string fileName) { List <ImapProxy> imapProxies = new List <ImapProxy>(); try { if (File.Exists(fileName)) { XPathDocument document = new XPathDocument(fileName); XPathNavigator navigator = document.CreateNavigator(); int imapServiceCount = ProxyFunctions.GetXmlIntValue(navigator, "/Settings/IMAP/ServiceCount"); for (int i = 1; i <= imapServiceCount; i++) { ImapProxyArguments arguments = new ImapProxyArguments(); arguments.AcceptedIPs = ProxyFunctions.GetXmlStringValue(navigator, "/Settings/SMTP/Service" + i + "/AcceptedIPs"); string localIpAddress = ProxyFunctions.GetXmlStringValue(navigator, "/Settings/IMAP/Service" + i + "/LocalIPAddress").ToUpper(); switch (localIpAddress) { // Treat blank values as "Any". case "": case "ANY": arguments.LocalIpAddress = IPAddress.Any; break; case "BROADCAST": arguments.LocalIpAddress = IPAddress.Broadcast; break; case "IPV6ANY": arguments.LocalIpAddress = IPAddress.IPv6Any; break; case "IPV6LOOPBACK": arguments.LocalIpAddress = IPAddress.IPv6Loopback; break; case "LOOPBACK": arguments.LocalIpAddress = IPAddress.Loopback; break; default: // Try to parse the local IP address. If unable to, proceed to the next service instance. if (!IPAddress.TryParse(localIpAddress, out arguments.LocalIpAddress)) { continue; } break; } arguments.LocalPort = ProxyFunctions.GetXmlIntValue(navigator, "/Settings/IMAP/Service" + i + "/LocalPort"); // If the port is invalid, proceed to the next service instance. if (arguments.LocalPort < 1) { continue; } arguments.LocalEnableSsl = ProxyFunctions.GetXmlBoolValue(navigator, "/Settings/IMAP/Service" + i + "/LocalEnableSSL"); arguments.RemoteServerHostName = ProxyFunctions.GetXmlStringValue(navigator, "/Settings/IMAP/Service" + i + "/RemoteServerHostName"); // If the host name is invalid, proceed to the next service instance. if (string.IsNullOrEmpty(arguments.RemoteServerHostName)) { continue; } arguments.RemoteServerPort = ProxyFunctions.GetXmlIntValue(navigator, "/Settings/IMAP/Service" + i + "/RemoteServerPort"); // If the port is invalid, proceed to the next service instance. if (arguments.RemoteServerPort < 1) { continue; } arguments.RemoteServerEnableSsl = ProxyFunctions.GetXmlBoolValue(navigator, "/Settings/IMAP/Service" + i + "/RemoteServerEnableSSL"); string remoteServerUsername = ProxyFunctions.GetXmlStringValue(navigator, "/Settings/IMAP/Service" + i + "/RemoteServerUsername"); if (!string.IsNullOrEmpty(remoteServerUsername)) { arguments.RemoteServerCredential = new NetworkCredential(); arguments.RemoteServerCredential.UserName = remoteServerUsername; arguments.RemoteServerCredential.Password = ProxyFunctions.GetXmlStringValue(navigator, "/Settings/IMAP/Service" + i + "/RemoteServerPassword"); } string certificateLocationValue = ProxyFunctions.GetXmlStringValue(navigator, "/Settings/IMAP/Service" + i + "/Certificate/Location"); StoreLocation certificateLocation = StoreLocation.LocalMachine; if (certificateLocationValue.ToUpper() == "CURRENTUSER") { certificateLocation = StoreLocation.CurrentUser; } // Try to load the signing certificate based on its serial number first, then fallback to its subject name. string certificateValue = ProxyFunctions.GetXmlStringValue(navigator, "/Settings/IMAP/Service" + i + "/Certificate/SerialNumber"); if (!string.IsNullOrEmpty(certificateValue)) { arguments.Certificate = CertHelper.GetCertificateBySerialNumber(certificateLocation, certificateValue); } else { certificateValue = ProxyFunctions.GetXmlStringValue(navigator, "/Settings/IMAP/Service" + i + "/Certificate/SubjectName"); if (!string.IsNullOrEmpty(certificateValue)) { arguments.Certificate = CertHelper.GetCertificateBySubjectName(certificateLocation, certificateValue); } } arguments.ExportDirectory = ProxyFunctions.GetXmlStringValue(navigator, "Settings/IMAP/Service" + i + "/ExportDirectory"); arguments.LogFile = ProxyFunctions.GetXmlStringValue(navigator, "Settings/IMAP/Service" + i + "/LogFile"); string logLevel = ProxyFunctions.GetXmlStringValue(navigator, "Settings/IMAP/Service" + i + "/LogLevel"); switch (logLevel.ToUpper()) { case "NONE": arguments.LogLevel = LogLevel.None; break; case "CRITICAL": arguments.LogLevel = LogLevel.Critical; break; case "ERROR": arguments.LogLevel = LogLevel.Error; break; case "RAW": arguments.LogLevel = LogLevel.Raw; break; case "VERBOSE": arguments.LogLevel = LogLevel.Verbose; break; case "WARNING": arguments.LogLevel = LogLevel.Warning; break; case "INFORMATION": default: arguments.LogLevel = LogLevel.Information; break; } arguments.InstanceId = i; arguments.DebugMode = ProxyFunctions.GetXmlBoolValue(navigator, "Settings/IMAP/Service" + i + "/Debug"); // Remember the proxy in order to close it when the service stops. arguments.Proxy = new ImapProxy(); imapProxies.Add(arguments.Proxy); Thread proxyThread = new Thread(new ParameterizedThreadStart(StartProxy)); proxyThread.Name = "OpaqueMail IMAP Proxy"; proxyThread.Start(arguments); } } } catch { // Ignore errors if the XML settings file is malformed. } return(imapProxies); }
public static void Install(X509Certificate2 certificate, StoreName storeName = StoreName.Root, StoreLocation storeLocation = StoreLocation.LocalMachine) { var store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadWrite); store.Add(certificate); store.Close(); }
public static void FoundCertWithPrivateKey(this ILogger <HttpsConnectionMiddleware> logger, X509Certificate2 certificate, StoreLocation storeLocation) { var storeLocationString = storeLocation == StoreLocation.LocalMachine ? nameof(StoreLocation.LocalMachine) : nameof(StoreLocation.CurrentUser); FoundCertWithPrivateKey(logger, certificate.Thumbprint, storeLocationString); }
public X509Store(StoreName storeName, StoreLocation storeLocation, OpenFlags flags) : this(storeName, storeLocation) { Open(flags); }
public X509StoreIsAvailableAttribute(StoreName name, StoreLocation location) { Name = name; Location = location; }
static private X509Certificate2 GetCerificateFromStore(string serialNumber, StoreName storeName, StoreLocation storeLocation, bool validOnly = false) { if (string.IsNullOrWhiteSpace(serialNumber)) { throw new CustomArgumentException("Для поиска сертификата в хранилище сертификатов укажите корректно серийный номер!"); } X509Certificate2 certificate = null; var store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly); var coll = store.Certificates.Find(X509FindType.FindBySerialNumber, serialNumber, validOnly); if (coll.Count > 0) { certificate = coll[0]; } store.Close(); return(certificate); }
/// <summary> /// Gets a certificate from the given store by its thumbprint. /// </summary> /// <param name="storeName">The store name.</param> /// <param name="storeLocation">The store location.</param> /// <param name="thumbprint">The thumbprint.</param> /// <param name="validOnly">A value indicating whether only valid certificates are to be returned.</param> /// <returns>The certificate, if it exists.</returns> /// <exception cref="System.IO.FileNotFoundException"> /// The certificate does not exist. /// </exception> /// <exception cref="System.ArgumentException"> /// More than one certificate matched the criteria. /// </exception> public X509Certificate2 GetByThumbprint(StoreName storeName, StoreLocation storeLocation, string thumbprint, bool validOnly) { return(GetCertificate(storeName, storeLocation, X509FindType.FindByThumbprint, thumbprint, validOnly)); }
public static void SetCredentials <T, C>(this DuplexChannelFactory <T, C> factory, StoreLocation storeLocation, StoreName storeName, X509FindType findType, string clientCertificateName) where T : class { if (factory.State == CommunicationState.Opened) { throw new InvalidOperationException("Proxy channel is already opened"); } factory.Credentials.ClientCertificate.SetCertificate(storeLocation, storeName, findType, clientCertificateName); Collection <ServiceEndpoint> endpoints = new Collection <ServiceEndpoint>(); endpoints.Add(factory.Endpoint); SecurityBehavior.ConfigureBusinessToBusiness(endpoints); factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust; }
public X509Store(StoreLocation storeLocation) : this("MY", storeLocation) { }
internal void initialize() { if (_initialized) { return; } const string prefix = "IceSSL."; Ice.Properties properties = communicator().getProperties(); // // Check for a default directory. We look in this directory for // files mentioned in the configuration. // _defaultDir = properties.getProperty(prefix + "DefaultDir"); string certStoreLocation = properties.getPropertyWithDefault(prefix + "CertStoreLocation", "CurrentUser"); StoreLocation storeLocation; if (certStoreLocation == "CurrentUser") { storeLocation = StoreLocation.CurrentUser; } else if (certStoreLocation == "LocalMachine") { storeLocation = StoreLocation.LocalMachine; } else { _logger.warning("Invalid IceSSL.CertStoreLocation value `" + certStoreLocation + "' adjusted to `CurrentUser'"); storeLocation = StoreLocation.CurrentUser; } _useMachineContext = certStoreLocation == "LocalMachine"; // // Protocols selects which protocols to enable, by default we only enable TLS1.0 // TLS1.1 and TLS1.2 to avoid security issues with SSLv3 // var protocols = properties.getPropertyAsList(prefix + "Protocols"); if (protocols.Length > 0) { _protocols = parseProtocols(protocols); } else { _protocols = 0; foreach (int v in Enum.GetValues(typeof(SslProtocols))) { #pragma warning disable CS0618 // Type or member is obsolete if (v > (int)SslProtocols.Ssl3 && v != (int)SslProtocols.Default) #pragma warning restore CS0618 // Type or member is obsolete { _protocols |= (SslProtocols)v; } } } // // CheckCertName determines whether we compare the name in a peer's // certificate against its hostname. // _checkCertName = properties.getPropertyAsIntWithDefault(prefix + "CheckCertName", 0) > 0; // // VerifyDepthMax establishes the maximum length of a peer's certificate // chain, including the peer's certificate. A value of 0 means there is // no maximum. // _verifyDepthMax = properties.getPropertyAsIntWithDefault(prefix + "VerifyDepthMax", 3); // // CheckCRL determines whether the certificate revocation list is checked, and how strictly. // _checkCRL = properties.getPropertyAsIntWithDefault(prefix + "CheckCRL", 0); // // Check for a certificate verifier. // string certVerifierClass = properties.getProperty(prefix + "CertVerifier"); if (certVerifierClass.Length > 0) { if (_verifier != null) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: certificate verifier already installed"; throw e; } Type cls = _facade.findType(certVerifierClass); if (cls == null) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: unable to load certificate verifier class " + certVerifierClass; throw e; } try { _verifier = (CertificateVerifier)IceInternal.AssemblyUtil.createInstance(cls); } catch (Exception ex) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); e.reason = "IceSSL: unable to instantiate certificate verifier class " + certVerifierClass; throw e; } if (_verifier == null) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: unable to instantiate certificate verifier class " + certVerifierClass; throw e; } } // // Check for a password callback. // string passwordCallbackClass = properties.getProperty(prefix + "PasswordCallback"); if (passwordCallbackClass.Length > 0) { if (_passwordCallback != null) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: password callback already installed"; throw e; } Type cls = _facade.findType(passwordCallbackClass); if (cls == null) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass; throw e; } try { _passwordCallback = (PasswordCallback)IceInternal.AssemblyUtil.createInstance(cls); } catch (Exception ex) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass; throw e; } if (_passwordCallback == null) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass; throw e; } } // // If the user hasn't supplied a certificate collection, we need to examine // the property settings. // if (_certs == null) { // // If IceSSL.CertFile is defined, load a certificate from a file and // add it to the collection. // // TODO: tracing? _certs = new X509Certificate2Collection(); string certFile = properties.getProperty(prefix + "CertFile"); string passwordStr = properties.getProperty(prefix + "Password"); string findCert = properties.getProperty(prefix + "FindCert"); const string findPrefix = prefix + "FindCert."; Dictionary <string, string> findCertProps = properties.getPropertiesForPrefix(findPrefix); if (certFile.Length > 0) { if (!checkPath(ref certFile)) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: certificate file not found: " + certFile; throw e; } SecureString password = null; if (passwordStr.Length > 0) { password = createSecureString(passwordStr); } else if (_passwordCallback != null) { password = _passwordCallback.getPassword(certFile); } try { X509Certificate2 cert; X509KeyStorageFlags importFlags; if (_useMachineContext) { importFlags = X509KeyStorageFlags.MachineKeySet; } else { importFlags = X509KeyStorageFlags.UserKeySet; } if (password != null) { cert = new X509Certificate2(certFile, password, importFlags); } else { cert = new X509Certificate2(certFile, "", importFlags); } _certs.Add(cert); } catch (CryptographicException ex) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); e.reason = "IceSSL: error while attempting to load certificate from " + certFile; throw e; } } else if (findCert.Length > 0) { string certStore = properties.getPropertyWithDefault("IceSSL.CertStore", "My"); _certs.AddRange(findCertificates("IceSSL.FindCert", storeLocation, certStore, findCert)); if (_certs.Count == 0) { throw new Ice.PluginInitializationException("IceSSL: no certificates found"); } } else if (findCertProps.Count > 0) { // // If IceSSL.FindCert.* properties are defined, add the selected certificates // to the collection. // foreach (KeyValuePair <string, string> entry in findCertProps) { string name = entry.Key; string val = entry.Value; if (val.Length > 0) { string storeSpec = name.Substring(findPrefix.Length); StoreLocation storeLoc = 0; StoreName storeName = 0; string sname = null; parseStore(name, storeSpec, ref storeLoc, ref storeName, ref sname); if (sname == null) { sname = storeName.ToString(); } X509Certificate2Collection coll = findCertificates(name, storeLoc, sname, val); _certs.AddRange(coll); } } if (_certs.Count == 0) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: no certificates found"; throw e; } } } if (_caCerts == null) { string certAuthFile = properties.getProperty(prefix + "CAs"); if (certAuthFile.Length == 0) { certAuthFile = properties.getProperty(prefix + "CertAuthFile"); } if (certAuthFile.Length > 0 || properties.getPropertyAsInt(prefix + "UsePlatformCAs") <= 0) { _caCerts = new X509Certificate2Collection(); } if (certAuthFile.Length > 0) { if (!checkPath(ref certAuthFile)) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: CA certificate file not found: " + certAuthFile; throw e; } try { using (System.IO.FileStream fs = System.IO.File.OpenRead(certAuthFile)) { byte[] data = new byte[fs.Length]; fs.Read(data, 0, data.Length); string strbuf = ""; try { strbuf = System.Text.Encoding.UTF8.GetString(data); } catch (Exception) { // Ignore } if (strbuf.Length == data.Length) { int size, startpos, endpos = 0; bool first = true; while (true) { startpos = strbuf.IndexOf("-----BEGIN CERTIFICATE-----", endpos); if (startpos != -1) { endpos = strbuf.IndexOf("-----END CERTIFICATE-----", startpos); size = endpos - startpos + "-----END CERTIFICATE-----".Length; } else if (first) { startpos = 0; endpos = strbuf.Length; size = strbuf.Length; } else { break; } byte[] cert = new byte[size]; System.Buffer.BlockCopy(data, startpos, cert, 0, size); _caCerts.Import(cert); first = false; } } else { _caCerts.Import(data); } } } catch (Exception ex) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); e.reason = "IceSSL: error while attempting to load CA certificate from " + certAuthFile; throw e; } } } _initialized = true; }
/// <summary> /// Can only call before openning the host /// </summary> public static void SetSecurityBehavior(this ServiceHost host, ServiceSecurity mode, StoreLocation storeLocation, StoreName storeName, X509FindType findType, string serviceCertificateName, bool useAspNetProviders, string applicationName, bool impersonateAll) { if (host.State == CommunicationState.Opened) { throw new InvalidOperationException("Host is already opened"); } SecurityBehavior securityBehavior = new SecurityBehavior(mode, storeLocation, storeName, findType, serviceCertificateName); securityBehavior.UseAspNetProviders = useAspNetProviders; securityBehavior.ApplicationName = applicationName; securityBehavior.ImpersonateAll = impersonateAll; host.Description.Behaviors.Add(securityBehavior); }
public Task RunOnce(StoreLocation location, Func <Task> action) { return(RunOnce(location, action, TimeSpan.FromSeconds(5))); }
private static X509Certificate2Collection findCertificates(string prop, StoreLocation storeLocation, string name, string value) { // // Open the X509 certificate store. // X509Store store = null; try { try { store = new X509Store((StoreName)Enum.Parse(typeof(StoreName), name, true), storeLocation); } catch (ArgumentException) { store = new X509Store(name, storeLocation); } store.Open(OpenFlags.ReadOnly); } catch (Exception ex) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); e.reason = "IceSSL: failure while opening store specified by " + prop; throw e; } // // Start with all of the certificates in the collection and filter as necessary. // // - If the value is "*", return all certificates. // - Otherwise, search using key:value pairs. The following keys are supported: // // Issuer // IssuerDN // Serial // Subject // SubjectDN // SubjectKeyId // Thumbprint // // A value must be enclosed in single or double quotes if it contains whitespace. // X509Certificate2Collection result = new X509Certificate2Collection(); result.AddRange(store.Certificates); try { if (value != "*") { if (value.IndexOf(':') == -1) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: no key in `" + value + "'"; throw e; } int start = 0; int pos; while ((pos = value.IndexOf(':', start)) != -1) { // // Parse the X509FindType. // string field = value.Substring(start, pos - start).Trim().ToUpperInvariant(); X509FindType findType; if (field.Equals("SUBJECT")) { findType = X509FindType.FindBySubjectName; } else if (field.Equals("SUBJECTDN")) { findType = X509FindType.FindBySubjectDistinguishedName; } else if (field.Equals("ISSUER")) { findType = X509FindType.FindByIssuerName; } else if (field.Equals("ISSUERDN")) { findType = X509FindType.FindByIssuerDistinguishedName; } else if (field.Equals("THUMBPRINT")) { findType = X509FindType.FindByThumbprint; } else if (field.Equals("SUBJECTKEYID")) { findType = X509FindType.FindBySubjectKeyIdentifier; } else if (field.Equals("SERIAL")) { findType = X509FindType.FindBySerialNumber; } else { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: unknown key in `" + value + "'"; throw e; } // // Parse the argument. // start = pos + 1; while (start < value.Length && (value[start] == ' ' || value[start] == '\t')) { ++start; } if (start == value.Length) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: missing argument in `" + value + "'"; throw e; } string arg; if (value[start] == '"' || value[start] == '\'') { int end = start; ++end; while (end < value.Length) { if (value[end] == value[start] && value[end - 1] != '\\') { break; } ++end; } if (end == value.Length || value[end] != value[start]) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: unmatched quote in `" + value + "'"; throw e; } ++start; arg = value.Substring(start, end - start); start = end + 1; } else { char[] ws = new char[] { ' ', '\t' }; int end = value.IndexOfAny(ws, start); if (end == -1) { arg = value.Substring(start); start = value.Length; } else { arg = value.Substring(start, end - start); start = end + 1; } } // // Execute the query. // // TODO: allow user to specify a value for validOnly? // bool validOnly = false; if (findType == X509FindType.FindBySubjectDistinguishedName || findType == X509FindType.FindByIssuerDistinguishedName) { X500DistinguishedNameFlags[] flags = { X500DistinguishedNameFlags.None, X500DistinguishedNameFlags.Reversed, }; X500DistinguishedName dn = new X500DistinguishedName(arg); X509Certificate2Collection r = result; for (int i = 0; i < flags.Length; ++i) { r = result.Find(findType, dn.Decode(flags[i]), validOnly); if (r.Count > 0) { break; } } result = r; } else { result = result.Find(findType, arg, validOnly); } } } } finally { store.Close(); } return(result); }
private async Task <OptimisticStoreWriteResult> SaveDataInternal(StoreLocation location, Metadata metadata, UpdateAuditInfo audit, Func <IWriteAsyncStream, Task <long?> > savingFunc, CancellationToken token, bool isOptimistic) { var blob = GetBlockBlob(location); // We always want to save the new audit information when saving! var currentMetadata = await GetBlobMetadata(blob).ConfigureAwait(false); var auditInfo = TransformAuditInformation(currentMetadata, audit); metadata = metadata ?? new Metadata(); metadata.Audit = auditInfo; var result = new OptimisticStoreWriteResult() { Result = true }; try { // If the ETag value is empty then the store value must not exist yet... var condition = isOptimistic ? (string.IsNullOrEmpty(metadata.ETag) ? AccessCondition.GenerateIfNoneMatchCondition("*") : AccessCondition.GenerateIfMatchCondition(metadata.ETag)) : null; // Copy the metadata across blob.Metadata.Clear(); foreach (var m in metadata) { blob.Metadata[m.Key] = m.Value; } // Always store the version - We use this to do more efficient things on read blob.Metadata[StoreVersionKey] = StoreVersionValue; long?length; using (var stream = new AzureWriteBlockBlobStream(blob, condition)) { length = await savingFunc(stream).ConfigureAwait(false); await stream.Complete(token).ConfigureAwait(false); } if (length.HasValue && (metadata == null || !metadata.ContentLength.HasValue)) { blob.Metadata[MetadataConstants.ContentLengthMetadataKey] = length.Value.ToString(CultureInfo.InvariantCulture); // Save the length straight away before the snapshot... await blob.SetMetadataAsync(null, null, null, token).ConfigureAwait(false); } // Create a snapshot straight away on azure // Note: this shouldnt matter for cost as any blocks that are the same do not cost extra if (_enableSnapshots) { var snapshotBlob = await blob.CreateSnapshotAsync(blob.Metadata, null, null, null, token).ConfigureAwait(false); var snapshot = snapshotBlob.SnapshotTime.Value.UtcTicks.ToString(CultureInfo.InvariantCulture); // Save the snapshot back to original blob... blob.Metadata[InternalSnapshotKey] = snapshot; await blob.SetMetadataAsync(null, null, null, token).ConfigureAwait(false); LeoTrace.WriteLine("Created Snapshot: " + blob.Name); } result.Metadata = await GetActualMetadata(blob).ConfigureAwait(false); } catch (StorageException exc) { if (isOptimistic) { // First condition occurrs when the eTags do not match // Second condition when we specified no eTag (ie must be new blob) if (exc.RequestInformation.HttpStatusCode == (int)HttpStatusCode.PreconditionFailed || (exc.RequestInformation.HttpStatusCode == (int)HttpStatusCode.Conflict && exc.RequestInformation.ExtendedErrorInformation.ErrorCode == "BlobAlreadyExists")) { result.Result = false; } else { // Might have been a different error? throw exc.Wrap(blob.Name); } } else { if (exc.RequestInformation.HttpStatusCode == (int)HttpStatusCode.Conflict || exc.RequestInformation.ExtendedErrorInformation.ErrorCode == "LeaseIdMissing") { throw new LockException("The underlying storage is currently locked for save"); } // Might have been a different error? throw exc.Wrap(blob.Name); } } return(result); }
public X509StoreRepository(StoreName storeName, StoreLocation storeLocation) { _x509Store = new X509Store(storeName, storeLocation); _x509Store.Open(OpenFlags.ReadWrite); }
public void CanImportCertificateChain(string sampleCertificateId, string intermediateAuthorityThumbprint, string rootAuthorityThumbprint, StoreLocation storeLocation, string storeName) { var sampleCertificate = SampleCertificate.SampleCertificates[sampleCertificateId]; // intermediate and root authority certificates are always imported to LocalMachine var rootAuthorityStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine); rootAuthorityStore.Open(OpenFlags.ReadWrite); var intermediateAuthorityStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine); intermediateAuthorityStore.Open(OpenFlags.ReadWrite); RemoveChainCertificatesFromStore(rootAuthorityStore, intermediateAuthorityStore, "CC7ED077F0F292595A8166B01709E20C0884A5999", intermediateAuthorityThumbprint); sampleCertificate.EnsureCertificateNotInStore(storeName, storeLocation); WindowsX509CertificateStore.ImportCertificateToStore(Convert.FromBase64String(sampleCertificate.Base64Bytes()), sampleCertificate.Password, storeLocation, storeName, sampleCertificate.HasPrivateKey); sampleCertificate.AssertCertificateIsInStore(storeName, storeLocation); // Assert chain certificates were imported if (!string.IsNullOrEmpty(intermediateAuthorityThumbprint)) { AssertCertificateInStore(intermediateAuthorityStore, intermediateAuthorityThumbprint); } AssertCertificateInStore(rootAuthorityStore, rootAuthorityThumbprint); var certificate = sampleCertificate.GetCertificateFromStore(storeName, storeLocation); Assert.True(certificate.HasPrivateKey); sampleCertificate.EnsureCertificateNotInStore(storeName, storeLocation); RemoveChainCertificatesFromStore(rootAuthorityStore, intermediateAuthorityStore, rootAuthorityThumbprint, intermediateAuthorityThumbprint); }
public Task <OptimisticStoreWriteResult> TryOptimisticWrite(StoreLocation location, Metadata metadata, UpdateAuditInfo audit, Func <IWriteAsyncStream, Task <long?> > savingFunc, CancellationToken token) { return(SaveDataInternal(location, metadata, audit, savingFunc, token, true)); }
public static X509Certificate2Collection GetStoreCertificates(StoreName storeName, StoreLocation storeLocation, bool openExistingOnly) { using (X509Store store = new X509Store(storeName, storeLocation)) { OpenFlags flags = OpenFlags.ReadOnly | OpenFlags.IncludeArchived; if (openExistingOnly) { flags |= OpenFlags.OpenExistingOnly; } store.Open(flags); X509Certificate2Collection certificates = store.Certificates; return(certificates); } }
public async Task <Metadata> SaveData(StoreLocation location, Metadata metadata, UpdateAuditInfo audit, Func <IWriteAsyncStream, Task <long?> > savingFunc, CancellationToken token) { var result = await SaveDataInternal(location, metadata, audit, savingFunc, token, false).ConfigureAwait(false); return(result.Metadata); }
/// <summary> /// 非对称加密解密,通过安装在系统中的证书获取密钥。 /// </summary> /// <param name="storeName"></param> /// <param name="location"></param> /// <param name="certName">CN=myCerName...</param> public static IAsymmetricCrypto AsymmetricCrypto(StoreName storeName, StoreLocation location, string certName) { return(new BaseCertificate(storeName, location, certName)); }
public void ImportExistingCertificateShouldNotOverwriteExistingPrivateKeyRights(string sampleCertificateId, StoreLocation storeLocation, string storeName) { var sampleCertificate = SampleCertificate.SampleCertificates[sampleCertificateId]; sampleCertificate.EnsureCertificateNotInStore(storeName, storeLocation); WindowsX509CertificateStore.ImportCertificateToStore( Convert.FromBase64String(sampleCertificate.Base64Bytes()), sampleCertificate.Password, storeLocation, storeName, sampleCertificate.HasPrivateKey); WindowsX509CertificateStore.AddPrivateKeyAccessRules(sampleCertificate.Thumbprint, storeLocation, storeName, new List <PrivateKeyAccessRule> { new PrivateKeyAccessRule("BUILTIN\\Users", PrivateKeyAccess.FullControl) }); WindowsX509CertificateStore.ImportCertificateToStore( Convert.FromBase64String(sampleCertificate.Base64Bytes()), sampleCertificate.Password, storeLocation, storeName, sampleCertificate.HasPrivateKey); var privateKeySecurity = WindowsX509CertificateStore.GetPrivateKeySecurity(sampleCertificate.Thumbprint, storeLocation, storeName); AssertHasPrivateKeyRights(privateKeySecurity, "BUILTIN\\Users", CryptoKeyRights.GenericAll); sampleCertificate.EnsureCertificateNotInStore(storeName, storeLocation); }