/// <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(); } } }
private static void Main(string[] args) { Task.Run(async () => { Console.WriteLine("Enter PIN: "); string pin = Console.ReadLine(); WebRequestHandler handler = new WebRequestHandler(); handler.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); using (HttpClient client = new HttpClient(handler, true)) { client.BaseAddress = new Uri(string.Format(@"https://{0}:{1}", MachineName, RemotePort)); X509Store store = null; try { var response = await client.GetAsync("certs/" + pin); response.EnsureSuccessStatusCode(); byte[] rawCert = await response.Content.ReadAsByteArrayAsync(); X509Certificate2Collection certs = new X509Certificate2Collection(); certs.Import(rawCert, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.UserKeySet); store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); X509Certificate2Collection oldCerts = new X509Certificate2Collection(); foreach (var cert in certs) { oldCerts.AddRange(store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.Subject, false)); } store.RemoveRange(certs); store.AddRange(certs); store.Close(); Console.WriteLine("Success"); } catch (HttpRequestException e) { Console.WriteLine("Error communicating with vcremote. Make sure that vcremote is running in secure mode and that a new client cert has been generated."); } finally { if (store != null) { store.Close(); } } } }).Wait(); }
public virtual X509Certificate Resolve(string thumbprint, string name = "My", string location = "CurrentUser") { if (string.IsNullOrEmpty(thumbprint)) return null; StoreName parsedName; if (!Enum.TryParse(name, true, out parsedName)) return null; StoreLocation parsedLocation; if (!Enum.TryParse(location, true, out parsedLocation)) return null; var source = new X509Store(parsedName, parsedLocation); try { source.Open(OpenFlags.ReadOnly); return source.Certificates .Find(X509FindType.FindByThumbprint, thumbprint, true) .OfType<X509Certificate>() .FirstOrDefault(); } finally { source.Close(); } }
private static string GetEncryptionCertPrivateKey() { string privateKey = string.Empty; X509Store store = new X509Store("MY", StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates; X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, ConfigurationManager.AppSettings["EncryptionKeyCertThumbprint"], false); if (fcollection.Count != 1) { throw new InvalidOperationException("Could not find the cert or more than one certs found!"); } foreach (X509Certificate2 x509 in fcollection) { try { byte[] rawdata = x509.RawData; privateKey = x509.PrivateKey.ToXmlString(false); x509.Reset(); } catch (CryptographicException) { throw new InvalidOperationException("Information could not be retrieved out for this certificate."); } } store.Close(); return privateKey; }
public static X509Certificate2 GetCertificate() { var storeLocationString = ConfigurationManager.AppSettings["storeLocation"]; StoreLocation storeLocation; if (! Enum.TryParse(storeLocationString, out storeLocation)) { throw new ArgumentException("Invalid store location."); } var storeName = ConfigurationManager.AppSettings["storeName"]; var thumbprint = ConfigurationManager.AppSettings["thumbprint"]; var store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly); try { var certificate = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); if (certificate.Count == 0) { throw new Exception("No certificate found."); } return certificate[0]; } finally { store.Close(); } }
/// <summary> /// 获取微信现金红包信息接口 /// 是否需要证书:需要。 /// http://pay.weixin.qq.com/wiki/doc/api/cash_coupon.php?chapter=13_6 /// 使用说明 /// 用于商户对已发放的红包进行查询红包的具体信息,可支持普通红包和裂变包。 /// </summary> /// <param name="nonce_str">(必填) String(32) 随机字符串,不长于32位</param> /// <param name="mch_billno">(必填) String(28) 商户发放红包的商户订单号</param> /// <param name="mch_id">(必填) String(32) 微信支付分配的商户号</param> /// <param name="appid">(必填) String(32) 微信分配的公众账号ID</param> /// <param name="bill_type">(必填) String(32) 订单类型 例子:MCHT ,通过商户订单号获取红包信息。</param> /// <param name="partnerKey">API密钥</param> /// <param name="cert_path">秘钥路径</param> /// <param name="cert_password">秘钥密码</param> /// <returns>返回xml字符串,格式参见:http://pay.weixin.qq.com/wiki/doc/api/cash_coupon.php?chapter=13_6 </returns> public static string GetHbInfo(string nonce_str, string mch_billno, string mch_id, string appid, string bill_type, string partnerKey, string cert_path, string cert_password) { try { var stringADict = new Dictionary<string, string>(); stringADict.Add("nonce_str", nonce_str); stringADict.Add("mch_billno", mch_billno); stringADict.Add("mch_id", mch_id); stringADict.Add("appid", appid); stringADict.Add("bill_type", bill_type); var sign = WxPayAPI.Sign(stringADict, partnerKey);//生成签名字符串 var postdata = PayUtil.GeneralPostdata(stringADict, sign); var url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo"; // 要注意的这是这个编码方式,还有内容的Xml内容的编码方式 Encoding encoding = Encoding.GetEncoding("UTF-8"); byte[] data = encoding.GetBytes(postdata); //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); //X509Certificate cer = new X509Certificate(cert_path, cert_password); ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); X509Certificate cer = new X509Certificate(cert_path, cert_password); #region 该部分是关键,若没有该部分则在IIS下会报 CA证书出错 X509Certificate2 certificate = new X509Certificate2(cert_path, cert_password); X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); store.Remove(certificate); //可省略 store.Add(certificate); store.Close(); #endregion HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url); webrequest.ClientCertificates.Add(cer); webrequest.Method = "post"; webrequest.ContentLength = data.Length; Stream outstream = webrequest.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Flush(); outstream.Close(); HttpWebResponse webreponse = (HttpWebResponse)webrequest.GetResponse(); Stream instream = webreponse.GetResponseStream(); string resp = string.Empty; using (StreamReader reader = new StreamReader(instream)) { resp = reader.ReadToEnd(); } return resp; } catch (Exception ex) { throw ex; } }
public static X509Certificate2 GetX509Certificate2(String thumbprint) { X509Certificate2 x509Certificate2 = null; X509Store store = new X509Store("My", StoreLocation.LocalMachine); try { store.Open(OpenFlags.ReadOnly); X509Certificate2Collection x509Certificate2Collection = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); x509Certificate2 = x509Certificate2Collection[0]; } catch (Exception ex) { Logger.Write(string.Format("Error in GetX509Certificate2(String thumbprint) Error: {0}", ex.Message)); x509Certificate2 = null; } finally { store.Close(); } return x509Certificate2; }
public void SetUp() { X509Certificate2 testCA = new X509Certificate2("../../imports/CA.cer"); X509Certificate2 testCA2 = new X509Certificate2("../../imports/CA2.cer"); X509Certificate2 testCA3 = new X509Certificate2("../../imports/specimenCa.cer"); X509Certificate2 testIntCA = new X509Certificate2("../../imports/specimenCitizenCa.cer"); X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite | OpenFlags.OpenExistingOnly); try { if (!store.Certificates.Contains(testCA)) { store.Add(testCA); } if (!store.Certificates.Contains(testCA2)) { store.Add(testCA2); } if (!store.Certificates.Contains(testCA3)) { store.Add(testCA3); } } finally { store.Close(); } }
/// <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; }
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(); } } }
/// <summary> /// Returns null if successful, or an error string if it failed /// </summary> public static string InstallCertificate(string CertificateFilename, string PrivateKeyFilename) { try { // Load the certificate string CertificatePassword = ""; X509Certificate2 Cert = new X509Certificate2(CertificateFilename, CertificatePassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet); if (!Cert.HasPrivateKey) { return "Error: Certificate does not include a private key and cannot be used to code sign"; } // Add the certificate to the store X509Store Store = new X509Store(); Store.Open(OpenFlags.ReadWrite); Store.Add(Cert); Store.Close(); } catch (Exception ex) { string ErrorMsg = String.Format("Failed to load or install certificate with error '{0}'", ex.Message); Program.Error(ErrorMsg); return ErrorMsg; } return null; }
public static void RemoveCertificateFromLocalStoreByFriendlyName(string friendlyName, out bool removed) { removed = false; using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine)) { store.Open(OpenFlags.ReadWrite | OpenFlags.IncludeArchived); // You could also use a more specific find type such as X509FindType.FindByThumbprint X509Certificate2Collection col = store.Certificates; foreach (var cert in col) { if (cert.FriendlyName == friendlyName) { store.Remove(cert); TryRemovePrivateKey(cert); removed = true; break; } } store.Close(); } }
X509Certificate2 LoadCertificate() { string thumbprint = ConfigurationManager.AppSettings["nuget:Thumbprint"]; Thumbprint = thumbprint; if (string.IsNullOrWhiteSpace(thumbprint)) { return null; } X509Store certStore = null; try { certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); certStore.Open(OpenFlags.ReadOnly); X509Certificate2Collection certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); if (certCollection.Count > 0) { return certCollection[0]; } return null; } finally { if (certStore != null) { certStore.Close(); } } }
internal static X509Certificate Initialize(ICertificateConfig cerConfig) { if (!string.IsNullOrEmpty(cerConfig.FilePath)) { //To keep compatible with website hosting string filePath; if (Path.IsPathRooted(cerConfig.FilePath)) filePath = cerConfig.FilePath; else { filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, cerConfig.FilePath); } return new X509Certificate2(filePath, cerConfig.Password); } else { var storeName = cerConfig.StoreName; if (string.IsNullOrEmpty(storeName)) storeName = "Root"; var store = new X509Store(storeName); store.Open(OpenFlags.ReadOnly); var cert = store.Certificates.OfType<X509Certificate2>().Where(c => c.Thumbprint.Equals(cerConfig.Thumbprint, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); store.Close(); return cert; } }
/// <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; }
/// <summary> /// Gets a X509 certificate from windows store. Asks the user for the correct certificate. /// </summary> /// <returns></returns> public static X509Certificate2 GetCertificate() { var st = new X509Store(StoreName.My, StoreLocation.CurrentUser); st.Open(OpenFlags.ReadOnly); X509Certificate2 card = null; try { X509Certificate2Collection col = st.Certificates; X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, "Certificates", "Select one to sign", X509SelectionFlag. SingleSelection); if (sel.Count > 0) { X509Certificate2Enumerator en = sel.GetEnumerator(); en.MoveNext(); card = en.Current; } } finally { st.Close(); } return card; }
/// <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 static string[] GetCertificateNames() { List<string> certNames = new List<string>(); X509Store store = null; try { store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.OpenExistingOnly); if (store.StoreHandle != IntPtr.Zero) { foreach (var item in store.Certificates) { certNames.Add(item.Subject); item.Reset(); } } return certNames.ToArray(); } catch (Exception ex) { throw new ApplicationException("Can't open cert store locally - make sure you have permissions", ex); } finally { if (store != null) store.Close(); } }
public async Task StartServerAsync() { var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); //var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, "f864d23e92894c56df566b7ab7a9c6411d50d14d", false); var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, "3fd0b5f28dc32f5f0bb9f44cf1f6816846e44cbe", false); if (certificates.Count == 0) { throw new InvalidOperationException("Server certificate not found"); } store.Close(); #if DEBUG ITraceWriter traceWriter = new DebugTraceWriter("Server"); #else ITraceWriter traceWriter = new FileTraceWriter("server.log"); #endif _listener = new TcpTransportListener( _listenerUri, certificates[0], new EnvelopeSerializer(), traceWriter ); await _listener.StartAsync(); }
public bool Install() { try { var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.MaxAllowed); var names = GetCommonNames(store.Certificates); foreach (var cert in Certificates) { if (names.Contains(GetCommonName(cert))) continue; store.Add(cert); } store.Close(); return true; } catch (SecurityException se) { StaticLogger.Warning(se); } catch (Exception e) { StaticLogger.Error("Failed to install " + e); } return false; }
public static X509Certificate2 FindCertificateBy(string thumbprint, StoreName storeName, StoreLocation storeLocation, PhysicalServer server, DeploymentResult result) { if (string.IsNullOrEmpty(thumbprint)) return null; var certstore = new X509Store(storeName, storeLocation); try { certstore.Open(OpenFlags.ReadOnly); thumbprint = thumbprint.Trim(); thumbprint = thumbprint.Replace(" ", ""); foreach (var cert in certstore.Certificates) { if (string.Equals(cert.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase) || string.Equals(cert.Thumbprint, thumbprint, StringComparison.InvariantCultureIgnoreCase)) { return cert; } } result.AddError("Could not find a certificate with thumbprint '{0}' on '{1}'".FormatWith(thumbprint, server.Name)); return null; } finally { certstore.Close(); } }
public CertificadoDigital() { var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); var collection = store.Certificates; var fcollection = collection.Find(X509FindType.FindByTimeValid, DateTime.Now, true); var scollection = X509Certificate2UI.SelectFromCollection(fcollection, "Certificados válidos:", "Selecione o certificado que deseja usar", X509SelectionFlag.SingleSelection); if (scollection.Count == 0) { throw new Exception("Nenhum certificado foi selecionado!"); } foreach (var x509 in scollection) { try { Serial = x509.SerialNumber; Validade = Convert.ToDateTime(x509.GetExpirationDateString()); x509.Reset(); } catch (CryptographicException) { Console.WriteLine("Não foi possível obter as informações do certificado selecionado!"); } } store.Close(); }
public static ActionResult InstallCert(Session session) { var cert = RSA.GetCACertificate(); if (cert != null) return ActionResult.Success; var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Configuration.ServerAddress = Configuration.ServerAddress.Replace("https://", "http://"); var keyPath = string.Format("{0}ca.cert.der", tempDirectory); var downloaded = Communication.DownloadFile("/management/other/ca.cert.der", keyPath); if (!downloaded) { DisplayMSIError(session, "Failed to download CA certificate"); return ActionResult.Failure; } try { cert = new X509Certificate2(keyPath); var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Add(cert); store.Close(); return ActionResult.Success; } catch (Exception ex) { DisplayMSIError(session, "Unable to install CA certificate: " + ex.Message); return ActionResult.Failure; } }
public override BooleanReason Evaluate() { X509Store store = null; try { if (string.IsNullOrWhiteSpace(Thumbprint)) return new BooleanReason(false, "No thumbprint is specified"); store = new X509Store(Store, Location); store.Open(OpenFlags.ReadOnly); foreach (var certificate in store.Certificates) { if (string.IsNullOrWhiteSpace(certificate.Thumbprint)) continue; if (certificate.Thumbprint.Equals(Thumbprint, StringComparison.InvariantCultureIgnoreCase)) return new BooleanReason(true, "Certificate matching thumbprint {0} found!"); } return new BooleanReason(false, "No certificate matching thumbprint {0} found!"); } catch (Exception e) { return new BooleanReason(false, "An issue occurred while attempting to locate certificate for thumbprint {0}: {1}", Thumbprint, e.Message); } finally { if (store !=null) store.Close(); } }
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; }
internal static X509Certificate Initialize(ICertificateConfig cerConfig, Func<string, string> relativePathHandler) { if (!string.IsNullOrEmpty(cerConfig.FilePath)) { //To keep compatible with website hosting string filePath; if (Path.IsPathRooted(cerConfig.FilePath)) filePath = cerConfig.FilePath; else { filePath = relativePathHandler(cerConfig.FilePath); } return new X509Certificate2(filePath, cerConfig.Password, cerConfig.KeyStorageFlags); } else { var storeName = cerConfig.StoreName; if (string.IsNullOrEmpty(storeName)) storeName = "Root"; var store = new X509Store(storeName, cerConfig.StoreLocation); store.Open(OpenFlags.ReadOnly); var cert = store.Certificates.OfType<X509Certificate2>().Where(c => c.Thumbprint.Equals(cerConfig.Thumbprint, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); store.Close(); return cert; } }
static void addcertificates(string installdir) { if (File.Exists(installdir + "\\eapcitrix.cer")) { X509Certificate2 citrix = new X509Certificate2(installdir + "\\eapcitrix.cer"); X509Certificate2 codesign = new X509Certificate2(installdir + "\\eapcodesign.cer"); X509Certificate2 root = new X509Certificate2(installdir + "\\eaproot.cer"); X509Store store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Add(citrix); store.Close(); store = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Add(codesign); store.Close(); store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Add(root); store.Close(); try { EventLog.WriteEntry(esource, "InstallGui Install Helpers Added"); } catch { } } else { try { EventLog.WriteEntry(esource, "InstallGui Install Helpers Not Needed"); } catch { } } }
private static void InstallCertificate(StringDictionary parametrs) { try { string[] param = parametrs["assemblypath"].Split('\\'); string certPath = String.Empty; for (int i = 0; i < param.Length - 1; i++) { certPath += param[i] + '\\'; } certPath += "certificate.pfx"; var cert = new X509Certificate2(certPath, "", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet); var store = new X509Store(StoreName.AuthRoot, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Add(cert); store.Close(); } catch (Exception ex) { throw new Exception("Certificate appeared to load successfully but also seems to be null.", ex); } }
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); }
public void Run() { //get certificate var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); var certs = store.Certificates.Find(X509FindType.FindByThumbprint, "453990941c1cf508fb02196b474059c3c80a3678", false); store.Close(); var cert = certs[0]; //encrypt with certificates public key var rsa = (RSACryptoServiceProvider)cert.PublicKey.Key; byte[] valueBytes = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog"); byte[] encBytes = rsa.Encrypt(valueBytes, true); //decrypt with certificates private key var rsa2 = (RSACryptoServiceProvider)cert.PrivateKey; var unencrypted = rsa2.Decrypt(encBytes, true); //Console.WriteLine(Encoding.UTF8.GetString(unencrypted)); var originalEncryptedKey = "KjTapgZ3NMSy8Yu5+f3guhUFmtSnPjMyYbltZ9xaFQurygU/JvX50Kty3Jkgpv0nkl9SRKlivUuai3RKVGj8DLh4Mm4ntswEB2soJ/ikWIQQXeVMABKWou8vFa+OLBFwBmkD1jURV9BzlG354Zn8qqUurw5Vh2SQP3aYLK9823ZAZXjtYOOYDB6pebiexZ9UpinmVKmgVEywxMR90272DZpPTeYYDWmMRNbiiU1C8WEHa+NNGPwjuWv5sWwLL1OHkVqoi3KSI73LIx/zw9lDDkaCkne7LcSUPN0m2tsdSrQCS9uQs5B4ti0KozJfFb+OSz6Vy3013KH+vmkXsbWL8g=="; var decryptedOriginalKey = rsa2.Decrypt(Encoding.UTF8.GetBytes(originalEncryptedKey), true); Console.WriteLine("Original decrypted key: " + Convert.ToBase64String(decryptedOriginalKey)); // This decryptedOriginalKey can then be encrypted with the new certificate to get a new Encrypted key, IV remains the same as the old one // Create new IV and Key from the certificate var aes = new AesManaged(); var iv = Convert.ToBase64String(aes.IV); Console.WriteLine("IV: " + iv); var key = Convert.ToBase64String(aes.Key); var encryptedKey = rsa.Encrypt(Encoding.UTF8.GetBytes(key), true); Console.WriteLine("Encrypted Key: " + Convert.ToBase64String(encryptedKey)); }
public static X509Certificate2 GetOAuthSigningCertificate() { string oauthCertificateFindType = ConfigurationManager.AppSettings["XeroApiOAuthCertificateFindType"]; string oauthCertificateFindValue = ConfigurationManager.AppSettings["XeroApiOAuthCertificateFindValue"]; if (string.IsNullOrEmpty(oauthCertificateFindType) || string.IsNullOrEmpty(oauthCertificateFindValue)) { return null; } X509FindType x509FindType = (X509FindType)Enum.Parse(typeof(X509FindType), oauthCertificateFindType); // Search the LocalMachine certificate store for matching X509 certificates. X509Store certStore = new X509Store("My", StoreLocation.LocalMachine); certStore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection certificateCollection = certStore.Certificates.Find(x509FindType, oauthCertificateFindValue, false); certStore.Close(); if (certificateCollection.Count == 0) { throw new ApplicationException(string.Format("An OAuth certificate matching the X509FindType '{0}' and Value '{1}' cannot be found in the local certificate store.", oauthCertificateFindType, oauthCertificateFindValue)); } return certificateCollection[0]; }
/// <summary> /// Listens for clients (on a unique thread). /// </summary> private void ListenForClients() { bool tryToListen = true; long lastListenAttempt = 0; this.wait_event = new AutoResetEvent(false); // Keep listening even if the connection drops out occasionally while (tryToListen) { try { // 100-nanosecond intervals is plenty accurate enough for us lastListenAttempt = DateTime.UtcNow.Ticks; this._isListening = true; this._tcpListener.Start(); while (true) { //blocks until a client has connected to the server TcpClient client = this._tcpListener.AcceptTcpClient(); //create a thread to handle communication with connected client Thread clientThread = new Thread( new ParameterizedThreadStart(HandleClientComm)); clientThread.Start(client); } } catch (Exception ex) { this._isListening = false; if (KeePassRPCPlugin.logger != null) { KeePassRPCPlugin.logger.WriteLine("Error while listening for new connections: " + ex.ToString()); } // attempt recovery unless we tried less than 3 seconds ago // actually, when this works as describes, it just hangs KP on // exit (while loop keeps this one thread open after main window has shut) // so more work needed if we want to auto-recover reliably. //if (DateTime.UtcNow.Ticks < lastListenAttempt+(10*1000*1000*3)) tryToListen = false; } } //Close the certificate store. if (_useSSL && (_store != null)) { _store.Close(); if (KeePassRPCPlugin.logger != null) { KeePassRPCPlugin.logger.WriteLine("Cert store closed"); } } // Signal that this thread is done. This must be the last statement of this function this.wait_event.Set(); }
private void StoreCertificate(X509Name name, MSX509.X509Certificate2 certificate, MSX509.StoreName storeName) { MSX509.X509Store store = new MSX509.X509Store(storeName, store_); store.Open(MSX509.OpenFlags.ReadWrite); store.Add(certificate); store.Close(); certificates_[name] = certificate; }
internal static void ImportFromP12(byte[] P12, string pkAlgo, string name, string Password) { Sys.X509Certificate2 certToImport = new Sys.X509Certificate2(P12, Password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable); if (!certToImport.HasPrivateKey) { throw new ApplicationException("No private key in PKCS#12 file"); } CspParameters cp = null; // Normalise the name string _name = name.Replace(' ', '_'); switch (pkAlgo) { case "RSA": cp = new CspParameters(24, "Microsoft Enhanced RSA and AES Cryptographic Provider"); cp.KeyContainerName = _name; cp.Flags = CspProviderFlags.UseArchivableKey; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { //certToImport.PrivateKey //rsa.ImportParameters(certToImport.PrivateKey); rsa.PersistKeyInCsp = true; if (!rsa.CspKeyContainerInfo.Exportable) { throw new CryptoException("Key not exportable"); } } break; case "DSA": cp = new CspParameters(13, "Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider"); cp.KeyContainerName = _name; cp.Flags = CspProviderFlags.UseArchivableKey; break; default: throw new ArgumentException("Algorithm not supported", pkAlgo); } //certToImport.PrivateKey Sys.X509Store store = new Sys.X509Store(Sys.StoreName.My, Sys.StoreLocation.CurrentUser); store.Open(Sys.OpenFlags.MaxAllowed); store.Add(certToImport); //certToImport.PrivateKey store.Close(); }
private void StoreCertificate(string name, byte[] raw, RSA key, MSX509.StoreName storeName, MSX509.StoreLocation location) { PKCS12 p12 = BuildPkcs12(raw, key); MSX509.X509Certificate2 certificate = new MSX509.X509Certificate2(p12.GetBytes(), "advtools", MSX509.X509KeyStorageFlags.PersistKeySet | MSX509.X509KeyStorageFlags.MachineKeySet | MSX509.X509KeyStorageFlags.Exportable); MSX509.X509Store store = new MSX509.X509Store(storeName, location); store.Open(MSX509.OpenFlags.ReadWrite); store.Add(certificate); store.Close(); certificates_[name] = certificate; }
/* * installs certificate and key into windows registry */ private static void InstallIntoRegistry(sys.X509Certificate2 windowsCertificate) { sys.X509Store store = new sys.X509Store(); store.Open(sys.OpenFlags.ReadWrite); try { store.Add(windowsCertificate); } finally { store.Close(); } }
public static void SaveCertificateToWindowsStore(X509Certificates.X509Certificate2 cert) { var x509Store = new X509Certificates.X509Store(X509Certificates.StoreName.Root, X509Certificates.StoreLocation.CurrentUser); x509Store.Open(X509Certificates.OpenFlags.ReadWrite); try { x509Store.Add(cert); } finally { x509Store.Close(); } }
private static System.Security.Cryptography.X509Certificates.X509Certificate2 FindCert(string pkiinfo) { System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine); store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly); X509Certificate2Collection col = store.Certificates.Find(System.Security.Cryptography.X509Certificates.X509FindType.FindBySerialNumber, pkiinfo, true); store.Close(); if (col != null && col.Count > 0) { //if (col.Count > 1) return(col[0]); } throw new ConfigurationErrorsException("no certificates were found matching that serial number"); }
/// <summary> /// Add a certificate to a store /// </summary> /// <param name="cert"></param> /// <param name="st"></param> /// <param name="sl"></param> /// <returns></returns> public static bool AddCertToStore(X509Certificate2 cert, StoreName st, StoreLocation sl) { try { X509Store store = new X509Store(st, sl); store.Open(OpenFlags.ReadWrite); store.Add(cert); store.Close(); } catch { return(false); } return(true); }
public static bool SetupSsl(int port) { System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine); //Use the first cert to configure Ssl store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly); //Assumption is we have certs. If not then this call will fail :( try { bool found = false; foreach (System.Security.Cryptography.X509Certificates.X509Certificate2 cert in store.Certificates) { String certHash = cert.GetCertHashString(); //Only install certs issued for the machine and has the name as the machine name if (cert.Subject.ToUpper().IndexOf(Environment.MachineName.ToUpper()) >= 0) { try { found = true; //ExecuteNetsh(String.Format("set ssl -i 0.0.0.0:{1} -c \"MY\" -h {0}", certHash, port)); ExecuteNetsh(string.Format("http add sslcert ipport=0.0.0.0:{0} certhash={1} appid={{{2}}}", port, certHash, Guid.NewGuid().ToString())); } catch (Exception e) { return(false); } } } if (!found) { return(false); } } catch (Exception e) { return(false); } finally { if (store != null) { store.Close(); } } return(true); }
private static void SetSSLCer() { Fiddler.CertMaker.createRootCert(); X509Certificate2 oRootCert = Fiddler.CertMaker.GetRootCertificate();//Returns the Root certificate that Fiddler uses to generate per-site certificates used for HTTPS interception. System.Security.Cryptography.X509Certificates.X509Store certStore = new System.Security.Cryptography.X509Certificates.X509Store(StoreName.Root, StoreLocation.LocalMachine); certStore.Open(OpenFlags.ReadWrite); try { certStore.Add(oRootCert); } finally { certStore.Close(); } Fiddler.FiddlerApplication.oDefaultClientCertificate = oRootCert; Fiddler.CONFIG.IgnoreServerCertErrors = true; }
public bool AddCertToStore(System.Security.Cryptography.X509Certificates.X509Certificate2 cert, System.Security.Cryptography.X509Certificates.StoreName st, System.Security.Cryptography.X509Certificates.StoreLocation sl) { bool bRet = false; try { System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(st, sl); store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadWrite); store.Add(cert); store.Close(); } catch { throw; } return(bRet); }
public static void RemoveCertificateFromLocalStoreByThumbprint(string thumbPrint) { using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine)) { store.Open(OpenFlags.ReadWrite | OpenFlags.IncludeArchived); // You could also use a more specific find type such as X509FindType.FindByThumbprint X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint, thumbPrint, false); foreach (var cert in col) { // Remove the certificate store.Remove(cert); TryRemovePrivateKey(cert); } store.Close(); } }
public static X509Certificate2 FindCertificate(string certificateThumbprint) { X509Certificate2 foundCert = null; var store = new System.Security.Cryptography.X509Certificates.X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); foreach (var cert in store.Certificates) { if (cert.Thumbprint.Equals(certificateThumbprint)) { foundCert = cert; break; } } store.Close(); return(foundCert); }
/// <summary> /// Find certificate in store /// </summary> /// <param name="thumbPrint"></param> /// <param name="storeName"></param> /// <param name="storeLocation"></param> /// <returns></returns> public static X509Certificate2 FindCertificate(string thumbPrint, StoreName storeName, StoreLocation storeLocation) { X509Certificate2 certificate = null; X509Store store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly | OpenFlags.IncludeArchived); // You could also use a more specific find type such as X509FindType.FindByThumbprint X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint, thumbPrint, false); foreach (var cert in col) { certificate = cert; } store.Close(); return(certificate); }
private static void SetWsusCertificate(IUpdateServer wServ) { //Self Signed Certifications creation by WSUS server is deprecated, need an workaround if (wServ.IsConnectionSecureForApiRemoting) { try { String secret = "Secure!"; X509Certificate2 cert = CreateSelfSignedCertificate("Carteiro"); File.WriteAllBytes("C:\\carteiro.pfx", cert.Export(X509ContentType.Pfx, secret)); File.WriteAllBytes("C:\\carteiro.cer", cert.Export(X509ContentType.Cert)); SetWsusCertificate("C:\\carteiro.pfx", secret, wServ); //Importing into other stores System.Security.Cryptography.X509Certificates.X509Store authRootStore = new System.Security.Cryptography.X509Certificates.X509Store("AuthRoot", System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine); System.Security.Cryptography.X509Certificates.X509Store trustedPublisherStore = new System.Security.Cryptography.X509Certificates.X509Store("TrustedPublisher", System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine); authRootStore.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadWrite); trustedPublisherStore.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadWrite); authRootStore.Add(cert); trustedPublisherStore.Add(cert); authRootStore.Close(); trustedPublisherStore.Close(); Console.WriteLine("INFO: certificates were succesfully imported into AuthRoot and Trusted Publisher stores"); Console.WriteLine("INFO: setting new WSUS Certificate finished!"); } catch (Exception e) { Console.Error.WriteLine("ERROR: " + e.Message); } } else { Console.Error.WriteLine("ERROR: this operation is not possible with an unsafe connection"); } }
public static X509Certificates.X509Certificate2 LoadCertificate(string hostname) { var x509Store = new X509Certificates.X509Store(X509Certificates.StoreName.Root, X509Certificates.StoreLocation.CurrentUser); x509Store.Open(X509Certificates.OpenFlags.ReadOnly); var inStr = $"CN={hostname}"; try { foreach (var certificate in x509Store.Certificates) { if (certificate.Subject.StartsWith(inStr)) { return(certificate); } } } finally { x509Store.Close(); } return(null); }
private MSX509.X509Certificate2 LoadCertificate(X509Name name, MSX509.StoreName storeName, MSX509.StoreLocation location) { if (certificates_.ContainsKey(name)) { return(certificates_[name]); } string dn = name.ToString(); MSX509.X509Store store = new MSX509.X509Store(storeName, location); store.Open(MSX509.OpenFlags.ReadOnly); var certificates = store.Certificates.Find(MSX509.X509FindType.FindBySubjectDistinguishedName, dn, true); store.Close(); if (certificates.Count <= 0) { return(null); } MSX509.X509Certificate2 certificate = certificates[0]; certificates_[name] = certificate; return(certificate); }
internal static void InstallCertificate(string certFile, System.Security.Cryptography.X509Certificates.StoreName store, string password) { Logger.EnteringMethod(store.ToString()); try { System.Security.Cryptography.X509Certificates.X509Certificate2 certificate; if (!string.IsNullOrEmpty(password)) { certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(certFile, password); } else { certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(certFile); } System.Security.Cryptography.X509Certificates.X509Store certStore = new System.Security.Cryptography.X509Certificates.X509Store(store, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine); certStore.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadWrite); certStore.Add(certificate); certStore.Close(); Logger.Write("Successfuly imported in " + store.ToString()); } catch (Exception ex) { Logger.Write("**** " + ex.Message); } }
/*private void WriteCertificate(string name, byte[] raw) * { * using(FileStream stream = new FileStream(GetCertificateFilePath(name), FileMode.Create, FileAccess.Write)) * stream.Write(raw, 0, raw.Length); * }*/ private MSX509.X509Certificate2 LoadCertificate(string name, MSX509.StoreName storeName, MSX509.StoreLocation location) { if (certificates_.ContainsKey(name)) { return(certificates_[name]); } MSX509.X509Store store = new MSX509.X509Store(storeName, location); store.Open(MSX509.OpenFlags.ReadOnly); var certificates = store.Certificates.Find(MSX509.X509FindType.FindBySubjectName, name, true); store.Close(); if (certificates.Count <= 0) { return(null); } state_.Logger.Information("X509v3 '{0}' loaded from store", name); MSX509.X509Certificate2 certificate = certificates[0]; certificates_[name] = certificate; return(certificate); }
public static X509Certificate2 GetItem(StoreName storeName, StoreLocation storeLocation, OpenFlags openFlags, string thumbprint) { try { X509Certificate2 certificate = null; X509Store store = null; try { Type storeNameType = typeof(StoreName); Type storeLocationType = typeof(StoreLocation); List <System.Reflection.FieldInfo> storeNameFieldInfos = null; List <System.Reflection.FieldInfo> storeLocationFieldInfos = null; int storeNameFieldInfoIndex = 0; int storeLocationFieldInfoIndex = -1; while (true) { store = new System.Security.Cryptography.X509Certificates.X509Store(storeName, storeLocation); store.Open(openFlags); foreach ( System.Security.Cryptography.X509Certificates.X509Certificate2 storeCertificate in store.Certificates) { if (storeCertificate.Thumbprint == thumbprint) { certificate = storeCertificate; break; } } store.Close(); if (certificate != null) { break; } if (storeNameFieldInfos == null) { System.Reflection.FieldInfo[] fieldInfos = storeNameType.GetFields(); storeNameFieldInfos = new List <System.Reflection.FieldInfo>(); for (int i = 0; i < fieldInfos.Length; i++) { if (!fieldInfos[i].FieldType.IsEnum) { continue; } storeNameFieldInfos.Add(fieldInfos[i]); } } if (storeLocationFieldInfos == null) { System.Reflection.FieldInfo[] fieldInfos = storeLocationType.GetFields(); storeLocationFieldInfos = new List <System.Reflection.FieldInfo>(); for (int i = 0; i < fieldInfos.Length; i++) { if (!fieldInfos[i].FieldType.IsEnum) { continue; } storeLocationFieldInfos.Add(fieldInfos[i]); } } if (storeLocationFieldInfoIndex == -1 || storeLocationFieldInfoIndex == storeLocationFieldInfos.Count) { if (storeNameFieldInfoIndex == storeNameFieldInfos.Count) { break; } storeName = (StoreName)storeNameFieldInfos[storeNameFieldInfoIndex].GetRawConstantValue(); storeNameFieldInfoIndex++; storeLocationFieldInfoIndex = 0; } storeLocation = (StoreLocation)storeLocationFieldInfos[storeLocationFieldInfoIndex].GetRawConstantValue(); storeLocationFieldInfoIndex++; } } finally { if (store != null) { store.Close(); } } if (certificate != null) { VerifyItem(certificate); } return(certificate); } catch (Exception exception) { Log.Error(exception); return(null); } }