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(); } }
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); } }
public void ReadCertStore() { using var store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly); Console.WriteLine($"Store: \\\\{storeLocation.ToString()}\\{storeName.ToString()}"); foreach (var cert in store.Certificates) { Console.WriteLine($"{cert.Subject.Substring(1, subjectLength)} : {cert.Thumbprint}"); } store.Close(); }
public void Write(StoreLocation storeLocation, StoreName storeName, X509Certificate2 obj) { try { recordCounter++; var cmd = new SqliteCommand(SQL_INSERT, DatabaseManager.Connection, DatabaseManager.Transaction); cmd.Parameters.AddWithValue("@run_id", runId); cmd.Parameters.AddWithValue("@store_location", storeLocation.ToString()); cmd.Parameters.AddWithValue("@store_name", storeName.ToString()); cmd.Parameters.AddWithValue("@hash", obj.GetCertHashString()); cmd.Parameters.AddWithValue("@hash_plus_store", obj.GetCertHashString() + storeLocation.ToString() + storeName.ToString()); cmd.Parameters.AddWithValue("@cn", obj.Subject); if (obj.HasPrivateKey) { cmd.Parameters.AddWithValue("@pkcs12", "redacted"); } else { cmd.Parameters.AddWithValue("@pkcs12", obj.Export(X509ContentType.Pfx)); } cmd.Parameters.AddWithValue("@row_key", CryptoHelpers.CreateHash(runId + recordCounter)); var cert = new CertificateObject() { StoreLocation = storeLocation.ToString(), StoreName = storeName.ToString(), CertificateHashString = obj.GetCertHashString(), Subject = obj.Subject }; cmd.Parameters.AddWithValue("@serialized", JsonConvert.SerializeObject(cert)); cmd.ExecuteNonQuery(); } catch (NullReferenceException e) { Log.Warning(e.StackTrace); } catch (Microsoft.Data.Sqlite.SqliteException e) { Log.Warning(e.Message); //This catches duplicate certificates } catch (Exception e) { Log.Warning(e.GetType().ToString()); Log.Warning(e.StackTrace); } }
static bool Compare(StoreLocation loc, X509Certificate2Collection certs) { bool res = true; string regPath = "Software\\Microsoft\\SystemCertificates\\" + storeName + "\\Certificates"; Console.WriteLine(String.Empty); Console.WriteLine("Certificates found in: " + loc.ToString() + "\\" + regPath); RegistryKey keyLocation = loc == StoreLocation.CurrentUser ? Registry.CurrentUser : Registry.LocalMachine; RegistryKey rk = keyLocation.OpenSubKey(regPath, true); string[] subKeys = rk.GetSubKeyNames(); for (int i = 0; i < subKeys.Length; i++) { Console.WriteLine(subKeys[i]); //Now make sure each subkey name exists in certs if (certs.Find(X509FindType.FindByThumbprint, subKeys[i], false).Count == 0) { res = false; } else { res &= true; } } rk.Close(); return(res); }
private static void SaveConfig() { var dataFolder = ConfigurationManager.AppSettings["IDPDataDirectory"]; if (!Path.IsPathRooted(dataFolder)) { dataFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, dataFolder); } string path = Path.Combine(dataFolder, _configFileName); FileConfig conf = new FileConfig(); conf.BaseUrl = ServerBaseUrl; if (IDPCertificate != null) { conf.certThumbPrint = IDPCertificate.Thumbprint; conf.certLocation = _storeLocation.ToString(); conf.certStore = _storeName.ToString(); } FileStream fs = File.Create(path); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, conf); fs.Close(); }
/// <summary> /// Method that allows manager to stock the shelves and prompts them accordingly /// </summary> private void StockShelves() { _location = validation.ValidateString("Enter the store's name:"); _address = validation.ValidateAddress("Enter the store's address in format CityName, ST"); try{ _store = _storeLoBL.GetStore(_address, _location); if (_store == null) { Console.WriteLine("Store Not Found, please add the store"); return; } //_storeLoBL.RemoveStore(_address,_location); string breed = validation.ValidateString("Enter breed of the dog"); char gender = validation.ValidateGender("Enter gender of the dog either m or f"); double price = validation.ValidateDouble("Enter price of the dog in the form dollars.cents"); Dog dog = new Dog(breed, gender, price); int quant = validation.ValidateInt("How many? Just enter a number"); Console.WriteLine(_store.ToString()); _storeLoBL.AddItem(_store, dog, quant); //_storeLoBL.AddStoreLocation(_store); Console.WriteLine("Thanks!"); }catch (Exception e) { Log.Error(e.Message); Console.WriteLine("Error while stocking"); } }
internal X509Certificate2 GetApplicationCertificateFromStore() { HealthVaultPlatformTrace.LogCertLoading( "Opening cert store (read-only): {0}", _storeLocation.ToString()); RSACng rsaProvider = null; string thumbprint = null; X509Certificate2 result = null; X509Store store = new X509Store(_storeLocation); store.Open(OpenFlags.ReadOnly); try { HealthVaultPlatformTrace.LogCertLoading( "Looking for matching cert with subject: {0}", _certSubject); foreach (X509Certificate2 cert in store.Certificates) { if (string.Equals( cert.Subject, _certSubject, StringComparison.OrdinalIgnoreCase)) { HealthVaultPlatformTrace.LogCertLoading( "Found matching cert subject with thumbprint: {0}", cert.Thumbprint); thumbprint = cert.Thumbprint; HealthVaultPlatformTrace.LogCertLoading("Looking for private key"); rsaProvider = (RSACng)cert.GetRSAPrivateKey(); HealthVaultPlatformTrace.LogCertLoading("Private key found"); result = cert; break; } } } catch (CryptographicException e) { HealthVaultPlatformTrace.LogCertLoading( "Failed to retrieve private key for certificate: {0}", e.ToString()); } finally { store.Dispose(); } if (rsaProvider == null || string.IsNullOrEmpty(thumbprint)) { throw new SecurityException("CertificateNotFound"); } return(result); }
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> /// Retrieve a certificate from the indicated store by searching the subject name. /// Throw an exception if more (or less) than one valid certificate is found which /// has a subject name that contains the search string. /// </summary> /// <param name="loc"></param> /// <param name="substrSubject"></param> /// <returns></returns> protected X509Certificate2 GetCertificateFromStore(StoreLocation loc, string substrSubject) { X509Certificate2 cert; X509Store store = new X509Store(loc); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindBySubjectName, substrSubject, true); store.Close(); //more than one found? if (col.Count > 1) { throw new CryptographicException("MultipleCertsFound: " + col.Count.ToString() + " certificates found in " + loc.ToString() + " store which contain \"" + substrSubject + "\" in their subject line"); } //no certs found? if (col.Count == 0) { throw new CryptographicException("NoCertFound: no certificate found in " + loc.ToString() + " store which contains \"" + substrSubject + "\" in the subject line"); } //we got it cert = col[0]; return(cert); }
/// <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> /// Asks for all stores for a given beer and prints the response (store location) as it arrives from the server. /// </summary> /// <returns></returns> public async Task ListStores(string style, string name, string brewery) { try { Console.WriteLine(string.Format("*** ListStores: style={0} name={1} brewery={2}", style, name, brewery)); Beer request = new Beer { Style = style, Name = name, Brewery = brewery }; using (var call = _client.ListStores(request)) { var responseStream = call.ResponseStream; StringBuilder responseLog = new StringBuilder("Result: "); while (await responseStream.MoveNext()) { StoreLocation storeLocation = responseStream.Current; responseLog.Append(storeLocation.ToString()); } Console.WriteLine(responseLog.ToString() + "\n"); } } catch (RpcException e) { Console.WriteLine("RPC failed " + e); throw; } }
/// <summary> /// Initializes a new instance of the <see cref="T:X509CertificatePickerView"/> class. /// </summary> /// <param name="storeLocation">The store location.</param> /// <param name="storeName">Name of the store.</param> public X509CertificatePickerView(StoreLocation storeLocation, StoreName storeName) : this() { this.storeLocation = storeLocation; this.storeName = storeName; cbLocation.SelectedItem = storeLocation.ToString(); cbStore.SelectedItem = storeName.ToString(); }
private LocalCertificateKey() { _bind = new StringVectorBind(4, 4) .Add(() => StoreLocation.ToString(), x => StoreLocation = x.Parse <StoreLocation>(ignoreCase: true)) .Add(() => StoreName.ToString(), x => StoreName = x.Parse <StoreName>(ignoreCase: true)) .Add(() => Thumbprint, x => Thumbprint = x) .Add(() => RequirePrivateKey.ToString(), x => RequirePrivateKey = bool.Parse(x)); }
public static CertificateStoreLocation FromStoreLocation(StoreLocation location) { return(new CertificateStoreLocation( new SystemStoreLocationInfo() { Flags = (uint)location << 16, Name = location.ToString() })); }
public static CertificateStoreLocation FromStoreLocation(StoreLocation location) { return new CertificateStoreLocation( new SystemStoreLocationInfo() { Flags = (uint)location << 16, Name = location.ToString() }); }
public override string ToString() { var list = new List <string> { StoreLocation.ToString(), StoreName.ToString(), Thumbprint, }; return("/" + string.Join("/", list)); }
static X509Certificate2Collection Print(StoreLocation loc) { Console.WriteLine(String.Empty); Console.WriteLine("Certificates returned from: " + loc.ToString() + "\\" + storeName); X509Store store = new X509Store(storeName, loc); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certs = store.Certificates; foreach (X509Certificate2 cert in certs) { Console.WriteLine(cert.Thumbprint); } store.Close(); return(certs); }
public ExpectedJwtSecurityTokenRequirement ( uint? tokenSize = null, Int32? clock = null, uint? life = null, X509CertificateValidator cert = null, string name = JwtConstants.ReservedClaims.Sub, string role = null, X509RevocationMode? revMode = null, X509CertificateValidationMode? certMode = null, StoreLocation? storeLoc = null, ExpectedException expectedException = null, string handler = JwtSecurityTokenHandlerType, string requirement = Elements.JwtSecurityTokenRequirement, string attributeEx1 = "", string attributeEx2 = "", string attributeEx3 = "", string attributeEx4 = "", string elementEx1 = comment, string elementEx2 = comment, string elementEx3 = comment, string elementEx4 = comment, string elementEx5 = comment, string elementEx6 = comment, string elementClose = closeRequirement ) { MaxTokenSizeInBytes = tokenSize; NameClaimType = name; RoleClaimType = role; CertValidator = cert; ClockSkewInSeconds = clock; DefaultTokenLifetimeInMinutes = life; CertRevocationMode = revMode; CertValidationMode = certMode; CertStoreLocation = storeLoc; ExpectedException = expectedException ?? ExpectedException.NoExceptionExpected; string[] sParams = { handler, requirement, CertRevocationMode == null ? string.Empty : Attribute( Attributes.RevocationMode, CertRevocationMode.Value.ToString() ), attributeEx1, CertValidationMode == null ? string.Empty : Attribute( Attributes.ValidationMode, CertValidationMode.Value.ToString() ), attributeEx2, CertValidator == null ? string.Empty : Attribute( Attributes.Validator, CertValidator.GetType().ToString() +", System.IdentityModel.Tokens.Jwt.Tests" ), attributeEx3, CertStoreLocation == null ? string.Empty : Attribute( Attributes.TrustedStoreLocation, CertStoreLocation.ToString() ), attributeEx4, elementEx1, ClockSkewInSeconds == null ? string.Empty : ElementValue( Elements.MaxClockSkewInMinutes, ClockSkewInSeconds.Value.ToString() ), elementEx2, MaxTokenSizeInBytes == null ? string.Empty : ElementValue( Elements.MaxTokenSizeInBytes, MaxTokenSizeInBytes.Value.ToString() ), elementEx3, DefaultTokenLifetimeInMinutes == null ? string.Empty : ElementValue( Elements.DefaultTokenLifetimeInMinutes, DefaultTokenLifetimeInMinutes.Value.ToString() ), elementEx4, NameClaimType == null ? string.Empty : ElementValue( Elements.NameClaimType, NameClaimType ), elementEx5, RoleClaimType == null ? string.Empty : ElementValue( Elements.RoleClaimType, RoleClaimType ), elementEx6, elementClose, }; Config = string.Format(ElementTemplate, sParams); }
public void NewAzureLinuxVMWithoutPasswordAndNoSSHEnpoint() { try { _serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); //Create service vmPowershellCmdlets.NewAzureService(_serviceName, locationName); //Add installed certificate to the service PSObject certToUpload = vmPowershellCmdlets.RunPSScript( String.Format("Get-Item cert:\\{0}\\{1}\\{2}", certStoreLocation.ToString(), certStoreName.ToString(), _installedCert.Thumbprint))[0]; vmPowershellCmdlets.AddAzureCertificate(_serviceName, certToUpload); string newAzureLinuxVMName = Utilities.GetUniqueShortName("PSLinuxVM"); var key = vmPowershellCmdlets.NewAzureSSHKey(NewAzureSshKeyType.PublicKey, _installedCert.Thumbprint, keyPath); var sshKeysList = new Model.LinuxProvisioningConfigurationSet.SSHPublicKeyList(); sshKeysList.Add(key); // Add-AzureProvisioningConfig without password and NoSSHEndpoint var azureVMConfigInfo = new AzureVMConfigInfo(newAzureLinuxVMName, InstanceSize.Small.ToString(), _linuxImageName); var azureProvisioningConfig = new AzureProvisioningConfigInfo(username, noSshEndpoint: true, sSHPublicKeyList: sshKeysList); var persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null); PersistentVM vm = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo); // New-AzureVM vmPowershellCmdlets.NewAzureVM(_serviceName, new[] { vm }); Console.WriteLine("New Azure service with name:{0} created successfully.", _serviceName); Collection <InputEndpointContext> endpoints = vmPowershellCmdlets.GetAzureEndPoint(vmPowershellCmdlets.GetAzureVM(newAzureLinuxVMName, _serviceName)); Console.WriteLine("The number of endpoints: {0}", endpoints.Count); foreach (var ep in endpoints) { Utilities.PrintContext(ep); } Assert.AreEqual(0, endpoints.Count); pass = true; } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } }
public ShowMap(StoreLocation selected) { InitializeComponent(); String cord = selected.latitude + "," + selected.longitude + "," + "0.000"; browser.NavigateToString("<html><body><script type='text/javascript' src='http://maps.google.com/maps/api/js?sensor=false'></script><div style='overflow:hidden;height:500px;width:600px;'><div id='gmap_canvas' style='height:500px;width:600px;'></div><style>#gmap_canvas img{max-width:none!important;background:none!important}</style><a class='google-map-code' href='http://wptiger.com' id='get-map-data'>premium wordpress themes</a></div><script type='text/javascript'> function init_map(){var myOptions = {zoom:17,center:new google.maps.LatLng(" + selected.latitude + "," + selected.longitude + "),mapTypeId: google.maps.MapTypeId.ROADMAP};map = new google.maps.Map(document.getElementById('gmap_canvas'), myOptions);marker = new google.maps.Marker({map: map,position: new google.maps.LatLng(" + selected.latitude + ", " + selected.longitude + ")});}google.maps.event.addDomListener(window, 'load', init_map);</script></body></html>"); String weather = Weather.get(selected.city); if (weather != "") { String temp = weather.Substring(0, 2) + " Celsius"; temptxt.Text = temp; } else { MessageBox.Show("There where an Internet Error.Could not get the weather information.", "Connection problem", MessageBoxButton.OK, MessageBoxImage.Information); } locationtxt.Text = selected.ToString(); }
private static void AddValue(HeaderStoreItemInfo info, object value, StoreLocation location) { // Since we have the same pattern for all three store locations (raw, invalid, parsed), we use // this helper method to deal with adding values: // - if 'null' just set the store property to 'value' // - if 'List<T>' append 'value' to the end of the list // - if 'T', i.e. we have already a value stored (but no list), create a list, add the stored value // to the list and append 'value' at the end of the newly created list. Contract.Assert((info.Parser != null) || ((info.Parser == null) && (value.GetType() == typeof(string))), "If no parser is defined, then the value must be string."); object currentStoreValue = null; switch (location) { case StoreLocation.Raw: currentStoreValue = info.RawValue; AddValueToStoreValue <string>(info, value, ref currentStoreValue); info.RawValue = currentStoreValue; break; case StoreLocation.Invalid: currentStoreValue = info.InvalidValue; AddValueToStoreValue <string>(info, value, ref currentStoreValue); info.InvalidValue = currentStoreValue; break; case StoreLocation.Parsed: Contract.Assert((value == null) || (!(value is List <object>)), "Header value types must not derive from List<object> since this type is used internally to store " + "lists of values. So we would not be able to distinguish between a single value and a list of values."); currentStoreValue = info.ParsedValue; AddValueToStoreValue <object>(info, value, ref currentStoreValue); info.ParsedValue = currentStoreValue; break; default: Contract.Assert(false, "Unknown StoreLocation value: " + location.ToString()); break; } }
/// <summary> /// Installs the certificate into the certificate store chosen. /// If the certificate is sucessfully installed, this will be recorded in the Persistant Storage /// </summary> /// <param name="cert">Certificate to install</param> /// <param name="storeName">The certificate store to use</param> /// <param name="storeLocation">The location within the certificate store to use</param> /// <returns>False if the user declined</returns> public static void InstallCertificate(X509Certificate2 cert, StoreName storeName, StoreLocation storeLocation) { _ = cert ?? throw new ArgumentNullException(paramName: nameof(cert)); if (IsCertificateInstalled(cert, storeName, storeLocation)) { return; } using var certStore = new X509Store(storeName, storeLocation); certStore.Open(OpenFlags.ReadWrite); Debug.WriteLine("Writing '{0}' to cert store {1}:{2}", cert.FriendlyName, storeName.ToString(), storeLocation.ToString()); try { // add to certificate store certStore.Add(cert); // ^ Will produce a popup prompt when installing to the root store // if the certificate is not already installed // There fore you should predict this // and warn+instruct the user } catch (CryptographicException ex) { // if user selects No when prompted to install the CA if ((uint)ex.HResult == 0x800704C7) { throw new UserAbortException("User selected No when prompted for certificate"); } Debug.WriteLine("THIS SHOULD NOT HAPPEN"); Debug.Print(ex.ToString()); Debug.Assert(false); throw; // unknown exception } // keep track of that we've installed it PersistingStore.InstalledCertificates = PersistingStore.InstalledCertificates .Add(InstalledCertificate.FromCertificate(cert, storeName, storeLocation)); }
private static void SaveConfig() { string path = Path.Combine(ConfigHelper.GetIdpDataDirectory(), _configFileName); FileConfig conf = new FileConfig(); conf.BaseUrl = ServerBaseUrl; if (IDPCertificate != null) { conf.certThumbPrint = IDPCertificate.Thumbprint; conf.certLocation = _storeLocation.ToString(); conf.certStore = _storeName.ToString(); } using (FileStream fs = File.Create(path)) { XmlSerializer xs = new XmlSerializer(typeof(FileConfig)); xs.Serialize(fs, conf); } }
/// <summary> /// Searches for a certificate in certificate store and returns the matching certificate /// </summary> /// <param name="storeLocation">Store Location: This can be one of LocalMachine or UserName</param> /// <param name="storeName">Store Location: Currently this can only be My store.</param> /// <param name="masterKeyPath"></param> /// <param name="thumbprint">Certificate thumbprint</param> /// <param name="isSystemOp"></param> /// <returns>Matching certificate</returns> private X509Certificate2 GetCertificate(StoreLocation storeLocation, StoreName storeName, string masterKeyPath, string thumbprint, bool isSystemOp) { // Open specified certificate store X509Store certificateStore = null; try { certificateStore = new X509Store(storeName, storeLocation); certificateStore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); // Search for the specified certificate X509Certificate2Collection matchingCertificates = certificateStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); // Throw an exception if a cert with the specified thumbprint is not found if (matchingCertificates == null || matchingCertificates.Count == 0) { throw SQL.CertificateNotFound(thumbprint, storeName.ToString(), storeLocation.ToString(), isSystemOp); } X509Certificate2 certificate = matchingCertificates[0]; if (!certificate.HasPrivateKey) { // ensure the certificate has private key throw SQL.CertificateWithNoPrivateKey(masterKeyPath, isSystemOp); } // return the matching certificate return(certificate); } finally { // Close the certificate store if (certificateStore != null) { certificateStore.Close(); } } }
/// <summary> /// Checks if the certificate is installed into the chosen store /// </summary> /// <param name="cert">Certificate to install</param> /// <param name="storeName">The certificate store to use</param> /// <param name="storeLocation">The location within the certificate store to use</param> /// <returns>True if found</returns> public static bool UninstallCertificate(X509Certificate2 cert, StoreName storeName, StoreLocation storeLocation) { if (!IsCertificateInstalled(cert, storeName, storeLocation)) { return(false); } Debug.WriteLine("Removing '{0}' from cert store {1}:{2}", cert.FriendlyName, storeName.ToString(), storeLocation.ToString()); using var certStore = new X509Store(storeName, storeLocation); certStore.Open(OpenFlags.ReadWrite); try { // remove from certificate store certStore.Remove(cert); // ^ Will produce a popup prompt when installing to the root store // if the certificate is not already installed // There fore you should predict this // and warn+instruct the user } catch (CryptographicException ex) { // if user selects No when prompted to remove the CA if ((uint)ex.HResult == 0x800704C7) { return(false); } Debug.WriteLine("THIS SHOULD NOT HAPPEN"); Debug.Print(ex.ToString()); Debug.Assert(false); throw; // unknown exception } // if we're still able to find it, then it probably wasn't removed. return(!IsCertificateInstalled(cert, storeName, storeLocation)); // TODO: ^ might cause false negatives in the case where the cert came from LOCAL MACHINE, more testing needed }
public bool SelectInteropCertificate() { X509Certificate2 selectedCert = new X509Certificate2(); StoreLocation certificateStore = StoreLocation.CurrentUser; if ((selectedCert = SignatureProcessor.SelectCertificateUI(StoreLocation.CurrentUser)) == null) { certificateStore = StoreLocation.LocalMachine; selectedCert = SignatureProcessor.SelectCertificateUI(StoreLocation.LocalMachine); } /* selectedCert = SignatureProcessor.SelectCertificateUI(StoreLocation.CurrentUser) ?? SignatureProcessor.SelectCertificateUI(StoreLocation.LocalMachine); */ if (selectedCert != null) { SetConfigField("InteropCertificateThumbprint", selectedCert.Thumbprint); SetConfigField("InteropCertificateStore", certificateStore.ToString()); saveChangesToConfig(); //LoadConfig(); return true; } return false; }
private static void SaveConfig() { string path = Path.Combine(ConfigurationManager.AppSettings["IDPDataDirectory"], _configFileName); FileConfig conf = new FileConfig(); conf.BaseUrl = ServerBaseUrl; if (IDPCertificate != null) { conf.certThumbPrint = IDPCertificate.Thumbprint; conf.certLocation = _storeLocation.ToString(); conf.certStore = _storeName.ToString(); } FileStream fs = File.Create(path); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, conf); fs.Close(); }
public string[] Build() { string[] result = new string[10]; result[0] = $"-{nameof(StoreName)}"; result[1] = StoreName.ToString(); result[2] = $"-{nameof(StoreLocation)}"; result[3] = StoreLocation.ToString(); result[4] = $"-{nameof(X509FindType)}"; result[5] = X509FindType.ToString(); result[6] = $"-{nameof(OpenFlags)}"; result[7] = OpenFlags.ToString(); result[8] = $"-{nameof(FindValue)}"; result[9] = FindValue; return(result); }
internal StoreClientCertItem(XElement element, SettingsFile origin) : base(element, origin) { var storeLocation = element.Attribute(XName.Get(ConfigurationConstants.StoreLocationAttribute))?.Value; if (string.IsNullOrWhiteSpace(storeLocation)) { storeLocation = DefaultStoreLocation.ToString(); } AddAttribute(ConfigurationConstants.StoreLocationAttribute, storeLocation); var storeName = element.Attribute(XName.Get(ConfigurationConstants.StoreNameAttribute))?.Value; if (string.IsNullOrWhiteSpace(storeName)) { storeName = DefaultStoreName.ToString(); } AddAttribute(ConfigurationConstants.StoreNameAttribute, storeName); var findBy = element.Attribute(XName.Get(ConfigurationConstants.FindByAttribute))?.Value; if (string.IsNullOrWhiteSpace(findBy)) { findBy = GetString(DefaultFindBy); } AddAttribute(ConfigurationConstants.FindByAttribute, findBy); var findValue = element.Attribute(XName.Get(ConfigurationConstants.FindValueAttribute))?.Value; if (string.IsNullOrWhiteSpace(findValue)) { throw new ArgumentException(Resources.Argument_Cannot_Be_Null_Or_Empty); } AddAttribute(ConfigurationConstants.FindValueAttribute, findValue); }
static X509Certificate2Collection Print(StoreLocation loc) { Console.WriteLine( String.Empty ) ; Console.WriteLine( "Certificates returned from: " + loc.ToString() + "\\" + storeName ) ; X509Store store = new X509Store( storeName , loc) ; store.Open( OpenFlags.ReadOnly ) ; X509Certificate2Collection certs = store.Certificates ; foreach( X509Certificate2 cert in certs ) { Console.WriteLine( cert.Thumbprint ) ; } store.Close() ; return certs ; }
private static X509Certificate2 FindCertificate(string thumbprint, StoreLocation location) { X509Certificate2 certFound = null; using (var store = new X509Store(StoreName.My, location)) { store.Open(OpenFlags.ReadOnly); var certs = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); AppHealth.Current.Info.TrackAsync(string.Format(StringRes.TemplatePackageFindCertificateFoundMessage, certs.Count, thumbprint, location.ToString())).FireAndForget(); if (certs.Count >= 1) { certFound = certs[0]; if (certs.Count > 1) { AppHealth.Current.Warning.TrackAsync(StringRes.TemplatePackageFindCertificateNotOneMessage).FireAndForget(); } if (!certFound.HasPrivateKey) { AppHealth.Current.Info.TrackAsync(StringRes.TemplatePackageFindCertificateNoPkMessage).FireAndForget(); } } } return(certFound); }
/// <summary> /// Searches for a certificate in certificate store and returns the matching certificate /// </summary> /// <param name="storeLocation">Store Location: This can be one of LocalMachine or UserName</param> /// <param name="storeName">Store Location: Currently this can only be My store.</param> /// <param name="thumbprint">Certificate thumbprint</param> /// <returns>Matching certificate</returns> private X509Certificate2 GetCertificate(StoreLocation storeLocation, StoreName storeName, string masterKeyPath, string thumbprint, bool isSystemOp) { // Open specified certificate store X509Store certificateStore = null; try { certificateStore = new X509Store(storeName, storeLocation); certificateStore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); // Search for the specified certificate X509Certificate2Collection matchingCertificates = certificateStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); // Throw an exception if a cert with the specified thumbprint is not found if (matchingCertificates == null || matchingCertificates.Count == 0) { throw SQL.CertificateNotFound(thumbprint, storeName.ToString(), storeLocation.ToString(), isSystemOp); } X509Certificate2 certificate = matchingCertificates[0]; if (!certificate.HasPrivateKey) { // ensure the certificate has private key throw SQL.CertificateWithNoPrivateKey(masterKeyPath, isSystemOp); } // return the matching certificate return certificate; } finally { // Close the certificate store if (certificateStore != null) { certificateStore.Close(); } } }
public static X509Certificate2 Consultar(StoreName storeName, StoreLocation storeLocation, string valor, TipoConsultaCertificado tpConsultaTipoCertificado) { System.Security.Cryptography.X509Certificates.X509Certificate2 _X509Cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(); try { X509Store store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates; X509Certificate2Collection collection1 = (X509Certificate2Collection)collection.Find(X509FindType.FindByTimeValid, DateTime.Now, false); X509Certificate2Collection collection2 = (X509Certificate2Collection)collection.Find(X509FindType.FindByKeyUsage, X509KeyUsageFlags.DigitalSignature, false); LogHelper.GravarLog("StoreName=" + storeName.ToString() + " location=" + storeLocation.ToString()); if (valor == "") { //Exibe uma lista de certificado existentes na maquina do usuário X509Certificate2Collection scollection = X509Certificate2UI.SelectFromCollection(collection2, "Certificado(s) Digital(is) disponível(is)", "Selecione o Certificado Digital para uso no aplicativo", X509SelectionFlag.SingleSelection); if (scollection.Count > 0) { return(scollection[0]); } } else { //Consulta com base no tipo de solicitação X509Certificate2Collection scollection = null; switch (tpConsultaTipoCertificado) { case TipoConsultaCertificado.PorNome: scollection = (X509Certificate2Collection)collection2 .Find(X509FindType.FindBySubjectDistinguishedName, valor, false); break; case TipoConsultaCertificado.PorNroSerie: LogHelper.GravarLog("Listar os certificados"); foreach (var cert in store.Certificates) { string serial = cert.SerialNumber; LogHelper.GravarLog("certificado:" + serial + ".valor passado:" + valor + "."); if (string.Compare(serial, valor) == 0) { return(cert); } } break; } if (scollection != null) { if (scollection.Count > 0) { return(scollection[0]); } } } store.Close(); } catch (System.Exception ex) { string msg = string.Format("Erro ao consultar o cetificado digital:{0}", ex.Message); LogHelper.GravarLog("Erro BUSCA CERTIFICADO " + " \n " + ex.StackTrace); throw new Exception(msg); } return(null); }
public void AzureIaaSBVT() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); DateTime prevTime = DateTime.Now; string diskLabel1 = "disk1"; int diskSize1 = 30; int lunSlot1 = 0; string diskLabel2 = "disk2"; int diskSize2 = 50; int lunSlot2 = 2; string ep1Name = "tcp1"; int ep1LocalPort = 60010; int ep1PublicPort = 60011; string ep1LBSetName = "lbset1"; int ep1ProbePort = 60012; string ep1ProbePath = string.Empty; int? ep1ProbeInterval = 7; int? ep1ProbeTimeout = null; NetworkAclObject ep1AclObj = vmPowershellCmdlets.NewAzureAclConfig(); bool ep1DirectServerReturn = false; string ep2Name = "tcp2"; int ep2LocalPort = 60020; int ep2PublicPort = 60021; int ep2LocalPortChanged = 60030; int ep2PublicPortChanged = 60031; string ep2LBSetName = "lbset2"; int ep2ProbePort = 60022; string ep2ProbePath = @"/"; int? ep2ProbeInterval = null; int? ep2ProbeTimeout = 32; NetworkAclObject ep2AclObj = vmPowershellCmdlets.NewAzureAclConfig(); bool ep2DirectServerReturn = false; string cerFileName = "testcert.cer"; string thumbprintAlgorithm = "sha1"; try { // Create a certificate X509Certificate2 certCreated = Utilities.CreateCertificate(password); byte[] certData2 = certCreated.Export(X509ContentType.Cert); File.WriteAllBytes(cerFileName, certData2); // Install the .cer file to local machine. StoreLocation certStoreLocation = StoreLocation.CurrentUser; StoreName certStoreName = StoreName.My; X509Certificate2 installedCert = Utilities.InstallCert(cerFileName, certStoreLocation, certStoreName); PSObject certToUpload = vmPowershellCmdlets.RunPSScript( String.Format("Get-Item cert:\\{0}\\{1}\\{2}", certStoreLocation.ToString(), certStoreName.ToString(), installedCert.Thumbprint))[0]; string certData = Convert.ToBase64String(((X509Certificate2)certToUpload.BaseObject).RawData); string newAzureVMName = Utilities.GetUniqueShortName(vmNamePrefix); if (string.IsNullOrEmpty(imageName)) { imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); } RecordTimeTaken(ref prevTime); // // New-AzureService and verify with Get-AzureService // vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Assert.IsTrue(Verify.AzureService(serviceName, serviceName, locationName)); RecordTimeTaken(ref prevTime); // // Add-AzureCertificate and verify with Get-AzureCertificate // vmPowershellCmdlets.AddAzureCertificate(serviceName, certToUpload); Assert.IsTrue(Verify.AzureCertificate(serviceName, certCreated.Thumbprint, thumbprintAlgorithm, certData)); RecordTimeTaken(ref prevTime); // // Remove-AzureCertificate // vmPowershellCmdlets.RemoveAzureCertificate(serviceName, certCreated.Thumbprint, thumbprintAlgorithm); Assert.IsTrue(Utilities.CheckRemove(vmPowershellCmdlets.GetAzureCertificate, serviceName, certCreated.Thumbprint, thumbprintAlgorithm)); RecordTimeTaken(ref prevTime); // // New-AzureVMConfig // var azureVMConfigInfo = new AzureVMConfigInfo(newAzureVMName, InstanceSize.Small.ToString(), imageName); PersistentVM vm = vmPowershellCmdlets.NewAzureVMConfig(azureVMConfigInfo); RecordTimeTaken(ref prevTime); // // Add-AzureCertificate // vmPowershellCmdlets.AddAzureCertificate(serviceName, certToUpload); // // New-AzureCertificateSetting // CertificateSettingList certList = new CertificateSettingList(); certList.Add(vmPowershellCmdlets.NewAzureCertificateSetting(certStoreName.ToString(), installedCert.Thumbprint)); RecordTimeTaken(ref prevTime); // // Add-AzureProvisioningConfig // AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, certList, username, password); azureProvisioningConfig.Vm = vm; vm = vmPowershellCmdlets.AddAzureProvisioningConfig(azureProvisioningConfig); RecordTimeTaken(ref prevTime); // // Add-AzureDataDisk (two disks) // AddAzureDataDiskConfig azureDataDiskConfigInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, diskSize1, diskLabel1, lunSlot1); azureDataDiskConfigInfo1.Vm = vm; vm = vmPowershellCmdlets.AddAzureDataDisk(azureDataDiskConfigInfo1); AddAzureDataDiskConfig azureDataDiskConfigInfo2 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, diskSize2, diskLabel2, lunSlot2); azureDataDiskConfigInfo2.Vm = vm; vm = vmPowershellCmdlets.AddAzureDataDisk(azureDataDiskConfigInfo2); RecordTimeTaken(ref prevTime); // // Add-AzureEndpoint (two endpoints) // AzureEndPointConfigInfo azureEndPointConfigInfo1 = new AzureEndPointConfigInfo( AzureEndPointConfigInfo.ParameterSet.CustomProbe, ProtocolInfo.tcp, ep1LocalPort, ep1PublicPort, ep1Name, ep1LBSetName, ep1ProbePort, ProtocolInfo.tcp, ep1ProbePath, ep1ProbeInterval, ep1ProbeTimeout, ep1AclObj, ep1DirectServerReturn, null, null, LoadBalancerDistribution.SourceIP); azureEndPointConfigInfo1.Vm = vm; vm = vmPowershellCmdlets.AddAzureEndPoint(azureEndPointConfigInfo1); AzureEndPointConfigInfo azureEndPointConfigInfo2 = new AzureEndPointConfigInfo( AzureEndPointConfigInfo.ParameterSet.CustomProbe, ProtocolInfo.tcp, ep2LocalPort, ep2PublicPort, ep2Name, ep2LBSetName, ep2ProbePort, ProtocolInfo.http, ep2ProbePath, ep2ProbeInterval, ep2ProbeTimeout, ep2AclObj, ep2DirectServerReturn); azureEndPointConfigInfo2.Vm = vm; vm = vmPowershellCmdlets.AddAzureEndPoint(azureEndPointConfigInfo2); RecordTimeTaken(ref prevTime); // // Set-AzureAvailabilitySet // string testAVSetName = "testAVSet1"; vm = vmPowershellCmdlets.SetAzureAvailabilitySet(testAVSetName, vm); RecordTimeTaken(ref prevTime); // // New-AzureDns // string dnsName = "OpenDns1"; string ipAddress = "208.67.222.222"; DnsServer dns = vmPowershellCmdlets.NewAzureDns(dnsName, ipAddress); RecordTimeTaken(ref prevTime); // // New-AzureVM // vmPowershellCmdlets.NewAzureVM(serviceName, new[] { vm }, null, new[] { dns }, null, null, null, null); RecordTimeTaken(ref prevTime); // // Get-AzureVM without any parameter (List VMs) // var vmlist = vmPowershellCmdlets.GetAzureVM(); Console.WriteLine("The number of VMs: {0}", vmlist.Count); Assert.AreNotSame(0, vmlist.Count, "No VM exists!!!"); PersistentVMRoleListContext returnedVMlist = vmlist.First(item => item.ServiceName.Equals(serviceName) && item.Name.Equals(newAzureVMName)); Assert.IsNotNull(returnedVMlist, "Created VM does not exist!!!"); Utilities.PrintContext((PersistentVMRoleContext)returnedVMlist); // // Get-AzureVM // PersistentVMRoleContext returnedVM = vmPowershellCmdlets.GetAzureVM(newAzureVMName, serviceName); vm = returnedVM.VM; RecordTimeTaken(ref prevTime); // // Verify AzureDataDisk // Assert.IsTrue(Verify.AzureDataDisk(vm, diskLabel1, diskSize1, lunSlot1, HostCaching.None), "Data disk is not properly added"); Assert.IsTrue(Verify.AzureDataDisk(vm, diskLabel2, diskSize2, lunSlot2, HostCaching.None), "Data disk is not properly added"); Console.WriteLine("Data disk added correctly."); RecordTimeTaken(ref prevTime); // // Verify AzureEndpoint // Assert.IsTrue(Verify.AzureEndpoint(vm, new[] { azureEndPointConfigInfo1, azureEndPointConfigInfo2 })); // // Verify RDP & PowerShell Endpoints // var endpoints = vmPowershellCmdlets.GetAzureEndPoint(vm); Assert.IsTrue(endpoints.Count(e => e.Name == "PowerShell" && e.LocalPort == 5986 && e.Protocol == "tcp") == 1); Assert.IsTrue(endpoints.Count(e => e.Name == "RemoteDesktop" && e.LocalPort == 3389 && e.Protocol == "tcp") == 1); // // Verify AzureDns // Assert.IsTrue(Verify.AzureDns(vmPowershellCmdlets.GetAzureDeployment(serviceName).DnsSettings, dns)); // // Verify AzureAvailibilitySet // Assert.IsTrue(Verify.AzureAvailabilitySet(vm, testAVSetName)); // // Verify AzureOsDisk // Assert.IsTrue(Verify.AzureOsDisk(vm, "Windows", HostCaching.ReadWrite)); // // Set-AzureDataDisk // SetAzureDataDiskConfig setAzureDataDiskConfigInfo = new SetAzureDataDiskConfig(HostCaching.ReadOnly, lunSlot1); setAzureDataDiskConfigInfo.Vm = vm; vm = vmPowershellCmdlets.SetAzureDataDisk(setAzureDataDiskConfigInfo); RecordTimeTaken(ref prevTime); // // Remove-AzureDataDisk // RemoveAzureDataDiskConfig removeAzureDataDiskConfig = new RemoveAzureDataDiskConfig(lunSlot2, vm); vm = vmPowershellCmdlets.RemoveAzureDataDisk(removeAzureDataDiskConfig); RecordTimeTaken(ref prevTime); // // Set-AzureEndpoint // azureEndPointConfigInfo2 = new AzureEndPointConfigInfo( AzureEndPointConfigInfo.ParameterSet.CustomProbe, ProtocolInfo.tcp, ep2LocalPortChanged, ep2PublicPortChanged, ep2Name, ep2LBSetName, ep2ProbePort, ProtocolInfo.http, ep2ProbePath, ep2ProbeInterval, ep2ProbeTimeout, ep2AclObj, ep2DirectServerReturn); azureEndPointConfigInfo2.Vm = vm; vm = vmPowershellCmdlets.SetAzureEndPoint(azureEndPointConfigInfo2); RecordTimeTaken(ref prevTime); // // Remove-AzureEndpoint // vm = vmPowershellCmdlets.RemoveAzureEndPoint(azureEndPointConfigInfo1.EndpointName, vm); RecordTimeTaken(ref prevTime); // // Set-AzureVMSize // var vmSizeConfig = new SetAzureVMSizeConfig(InstanceSize.Medium.ToString()); vmSizeConfig.Vm = vm; vm = vmPowershellCmdlets.SetAzureVMSize(vmSizeConfig); RecordTimeTaken(ref prevTime); // // Set-AzureOSDisk // vm = vmPowershellCmdlets.SetAzureOSDisk(HostCaching.ReadOnly, vm); // // Update-AzureVM // vmPowershellCmdlets.UpdateAzureVM(newAzureVMName, serviceName, vm); RecordTimeTaken(ref prevTime); // // Get-AzureVM and Verify the VM // vm = vmPowershellCmdlets.GetAzureVM(newAzureVMName, serviceName).VM; // Verify setting data disk Assert.IsTrue(Verify.AzureDataDisk(vm, diskLabel1, diskSize1, lunSlot1, HostCaching.ReadOnly), "Data disk is not properly added"); // Verify removing a data disk Assert.AreEqual(1, vmPowershellCmdlets.GetAzureDataDisk(vm).Count, "DataDisk is not removed."); // Verify setting an endpoint Assert.IsTrue(Verify.AzureEndpoint(vm, new[] { azureEndPointConfigInfo2 })); // Verify removing an endpoint Assert.IsFalse(Verify.AzureEndpoint(vm, new[] { azureEndPointConfigInfo1 })); // Verify os disk Assert.IsTrue(Verify.AzureOsDisk(vm, "Windows", HostCaching.ReadOnly)); // // Remove-AzureVM // vmPowershellCmdlets.RemoveAzureVM(newAzureVMName, serviceName); RecordTimeTaken(ref prevTime); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureVMName, serviceName)); pass = true; } catch (Exception e) { Console.WriteLine(e.ToString()); throw; } }
public X509Certificate2 CreateCertificate( StoreLocation storeLocation, string storeName, string applicationName, string applicationUri, IList<string> hostNames, string organization, ushort keySize, ushort lifetimeInYears) { X509Certificate2 certificate = CreateCertificate( CertificateStoreType.Windows, storeLocation.ToString() + "\\" + storeName, applicationUri, applicationName, null, hostNames, keySize, (ushort)(lifetimeInYears * 12)); return certificate; }
public static string GetString(StoreLocation storeLocation) { return(storeLocation.ToString()); }
static bool Compare( StoreLocation loc , X509Certificate2Collection certs ) { bool res = true ; string regPath = "Software\\Microsoft\\SystemCertificates\\" + storeName + "\\Certificates" ; Console.WriteLine( String.Empty ) ; Console.WriteLine( "Certificates found in: " + loc.ToString() + "\\" + regPath ) ; RegistryKey keyLocation = loc == StoreLocation.CurrentUser ? Registry.CurrentUser : Registry.LocalMachine ; RegistryKey rk = keyLocation.OpenSubKey( regPath , true ) ; string[] subKeys = rk.GetSubKeyNames() ; for( int i = 0 ; i < subKeys.Length ; i++ ) { Console.WriteLine( subKeys[i] ) ; //Now make sure each subkey name exists in certs if( certs.Find( X509FindType.FindByThumbprint , subKeys[i] , false ).Count == 0 ) res = false ; else res &= true ; } rk.Close() ; return res ; }
internal X509Certificate2 GetApplicationCertificateFromStore( Guid applicationId, StoreLocation storeLocation, string certSubject) { if (certSubject == null) { certSubject = "CN=" + GetApplicationCertificateSubject(applicationId); } HealthVaultPlatformTrace.LogCertLoading( "Opening cert store (read-only): {0}", storeLocation.ToString()); RSACryptoServiceProvider rsaProvider = null; string thumbprint = null; X509Certificate2 result = null; X509Store store = new X509Store(storeLocation); store.Open(OpenFlags.ReadOnly); try { HealthVaultPlatformTrace.LogCertLoading( "Looking for matching cert with subject: {0}", certSubject); foreach (X509Certificate2 cert in store.Certificates) { if (String.Equals( cert.Subject, certSubject, StringComparison.OrdinalIgnoreCase)) { HealthVaultPlatformTrace.LogCertLoading( "Found matching cert subject with thumbprint: {0}", cert.Thumbprint); thumbprint = cert.Thumbprint; HealthVaultPlatformTrace.LogCertLoading("Looking for private key"); rsaProvider = (RSACryptoServiceProvider)cert.PrivateKey; HealthVaultPlatformTrace.LogCertLoading("Private key found"); result = cert; break; } } } catch (CryptographicException e) { HealthVaultPlatformTrace.LogCertLoading( "Failed to retrieve private key for certificate: {0}", e.ToString()); } finally { store.Close(); } if (rsaProvider == null || String.IsNullOrEmpty(thumbprint)) { throw new SecurityException( ResourceRetriever.FormatResourceString( "CertificateNotFound", certSubject, storeLocation)); } return result; }
/// <summary> /// Removes a certificate from a cert store in the local machine. /// </summary> /// <param name="certName">The name of the certificate file to remove.</param> /// <param name="storeName">Name of the certificate store.</param> /// <param name="storeLocation">Location of the certificate store.</param> public static void RemoveCertificate(string certName, StoreName storeName, StoreLocation storeLocation) { X509Store store = null; string certIssuerName = string.Format("CN={0}, OU=streaminsight, O=microsoft, C=us", certName); try { store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly | OpenFlags.ReadWrite); var allCertificates = from cert in store.Certificates.OfType<X509Certificate2>() where cert.Issuer.Equals(certIssuerName) select cert; foreach (X509Certificate2 cert in allCertificates) { store.Remove(cert); Console.WriteLine(string.Format("Removed certificate with thumbprint {0} from store '{1}', has private key: {2}.", cert.Thumbprint, storeName.ToString(), cert.HasPrivateKey)); } store.Close(); store = null; } catch (Exception ex) { throw new Exception(String.Format("Remove certificate hit exception, storeName={0} storeLocation={1}.", storeName.ToString(), storeLocation.ToString()), ex); } finally { if (store != null) { store.Close(); } } }
private X509Certificate2 GetCertificate(String findValue, X509FindType findType, StoreName storeName, StoreLocation storeLocation, bool valid) { X509Store certStore = new X509Store(storeName, storeLocation); certStore.Open(OpenFlags.ReadOnly); X509Certificate2Collection foundCerts = certStore.Certificates.Find(findType, findValue, valid); certStore.Close(); // Check if any certificates were found with the criteria if (foundCerts.Count == 0) { //Look to see if the certificate is there but expired. foundCerts = certStore.Certificates.Find(findType, findValue, false); certStore.Close(); if (foundCerts.Count == 1) { if (foundCerts[0].NotBefore != null && foundCerts[0].NotAfter != null) { var From = foundCerts[0].NotBefore.ToString("yyyy-MM-ddTHH:mm"); var To = foundCerts[0].NotAfter.ToString("yyyy-MM-ddTHH:mm"); IhiSearchValidateOutcome.QueryMetadata.ErrorMessge = $"A single certificate could be found in the store named '{storeName.ToString()}' and the store location of '{storeLocation.ToString()}' for the account in use by the IIS Application pool with the serial {findValue}. Yet, this certificate is expiried with the date range From: {From}, To: {To}. Review the systems certificates as they seem to be expired."; return(null); } } if (foundCerts.Count > 1) { IhiSearchValidateOutcome.QueryMetadata.ErrorMessge = $"More than one certificate could be found in the store named '{storeName.ToString()}' and the store location of '{storeLocation.ToString()}' for the account in use by the IIS Application pool with the serial {findValue}. Yet, all appear to be expiried. Review the systems certificates as they seem to be expired."; return(null); } IhiSearchValidateOutcome.QueryMetadata.ErrorMessge = $"The certificate could not be found in the store named '{storeName.ToString()}' and the store location of '{storeLocation.ToString()}' for the account in use by the IIS Application pool with the serial {findValue}."; return(null); } // Check if more than one certificate was found with the criteria if (foundCerts.Count > 1) { IhiSearchValidateOutcome.QueryMetadata.ErrorMessge = $"More than one certificate found in the store named '{storeName.ToString()}' and the store location of '{storeLocation.ToString()}' for the account in use by the IIS Application pool with the serial {findValue}."; return(null); } return(foundCerts[0]); }