/// <summary> /// Adds a certificate to a cert store in the local machine. /// </summary> /// <param name="certificate">The file path to find the certificate file.</param> /// <param name="storeName">Name of the certificate store.</param> /// <param name="storeLocation">Location of the certificate store.</param> public static void AddCertificate(X509Certificate2 certificate, StoreName storeName, StoreLocation storeLocation) { X509Store store = null; try { store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly | OpenFlags.ReadWrite); var certificates = from cert in store.Certificates.OfType<X509Certificate2>() where cert.Thumbprint == certificate.Thumbprint select cert; if (certificates.FirstOrDefault() == null) { store.Add(certificate); Console.WriteLine(string.Format("Added certificate with thumbprint {0} to store '{1}', has private key: {2}.", certificate.Thumbprint, storeName.ToString(), certificate.HasPrivateKey)); store.Close(); store = null; } } catch (Exception ex) { throw new Exception(String.Format("AddCert exception storeName={0} storeLocation={1}", storeName.ToString(), storeLocation.ToString()), ex); } finally { if (store != null) { store.Close(); } } }
public 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); } }
/// <summary> /// 验证结果调用 /// </summary> /// <param name="code">是否成功</param> /// <param name="goodsID">物品ID</param> /// <param name="repeatReceipt">是否是重复的订单凭据</param> /// <param name="receipt">回执,商户订单号等</param> public static void OnVerificationResult(int code, string goodsID, bool repeatReceipt, string receipt, string error, StoreName storeName) { try { if (onVerificationResultCallBack != null) { PayResult result = new PayResult(code, goodsID, error, storeName); Debug.Log("验证回调 code " + code + " goodsID " + goodsID); onVerificationResultCallBack(result); } } catch (Exception e) { Debug.LogError(e); } if (code == 0 || code == ErrorCodeDefine.StorePay_RepeatReceipt || repeatReceipt) { Debug.Log("订单确认" + goodsID); SDKManager.ConfirmPay(storeName.ToString(), goodsID, receipt); } //验证成功 if (code != 0) { Debug.LogError("凭据验证失败! goodID:" + goodsID); } }
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> /// 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)); }
/// <summary> /// Instantiates a CertData object from a certificate. /// </summary> /// <param storeName="storeLocation">The store storeLocation.</param> /// <param storeName="storeName">Name of the store.</param> /// <param storeName="certificate">The certificate.</param> /// <param storeName="computeKeyIdentifiersImmediately">if set to <see langword="true"/>, it computes the key identifier values immediately.</param> /// <param storeName="computePrivateKeyDataImmediately">if set to <see langword="true"/>, it computes the data related to the private key data immediately.</param> /// <returns></returns> internal static CertData FromCert( StoreLocation storeLocation, StoreName storeName, X509Certificate2 certificate, bool computeKeyIdentifiersImmediately, bool computePrivateKeyDataImmediately) { return(FromCert(storeLocation, storeName.ToString(), certificate, computeKeyIdentifiersImmediately, computePrivateKeyDataImmediately)); }
public static X509Certificate2Collection FindMatchingCertificates( StoreLocation storeLocation, StoreName storeName, X509FindType findType, string findValue, string secondaryFindValue, bool doTakeMostRecentOnly) { return(FindMatchingCertificates(storeLocation, storeName.ToString(), findType, findValue, secondaryFindValue, doTakeMostRecentOnly)); }
public override string ToString() { var list = new List <string> { StoreLocation.ToString(), StoreName.ToString(), Thumbprint, }; return("/" + string.Join("/", list)); }
protected override void ExtraInit() { listener = new IAPStoreListener(); List <ProductDefinition> products = new List <ProductDefinition>(); foreach (var item in productDefinitions) { ProductType productType = GoodsType2ProductType(item.goodsType); ProductDefinition p = new ProductDefinition(item.goodsID, productType); products.Add(p); } AppStore appStore = (AppStore)Enum.Parse(typeof(AppStore), storeName.ToString()); listener.Initialize(appStore, products); listener.onInitialized = OnInitialized; listener.onInitializeFailed = OnInitializeFailed; listener.onPurchaseFailed = OnPurchaseFailed; listener.onPurchaseSuccess = OnPurchaseSuccess; }
/// <summary> /// 获得预支付订单 /// </summary> /// <param name="e"></param> /// <param name="args"></param> private void OnPrePay(PrePay2Client e, object[] args) { if (e.storeName != GetStoreName()) { return; } Debug.LogWarning("OnPrePay=========:" + e.prepay_id + "=partnerId=="); //判断是否需要重发支付 if (SDKManager.GetReSendPay(storeName.ToString())) { OnPayInfo onPayInfo = new OnPayInfo(); onPayInfo.isSuccess = true; onPayInfo.goodsId = e.goodsID; onPayInfo.storeName = GetStoreName(); onPayInfo.receipt = e.mch_orderID; onPayInfo.price = payInfo.price; PayReSend.Instance.AddPrePayID(onPayInfo); } IndentListener(e.goodsID, e.mch_orderID, e.prepay_id, payInfo.price); }
public X509Store (StoreName storeName, StoreLocation storeLocation) { if ((storeName < StoreName.AddressBook) || (storeName > StoreName.TrustedPublisher)) throw new ArgumentException ("storeName"); if ((storeLocation < StoreLocation.CurrentUser) || (storeLocation > StoreLocation.LocalMachine)) throw new ArgumentException ("storeLocation"); switch (storeName) { case StoreName.CertificateAuthority: _name = "CA"; break; default: _name = storeName.ToString (); break; } _location = storeLocation; }
/// <summary> /// Configures TLS. /// </summary> /// <param name="builder">The builder to configure.</param> /// <param name="storeName">The certificate store to load the certificate from.</param> /// <param name="subject">The subject name for the certificate to load.</param> /// <param name="allowInvalid">Indicates if invalid certificates should be considered, such as self-signed certificates.</param> /// <param name="location">The store location to load the certificate from.</param> /// <param name="configureOptions">An Action to configure the <see cref="TlsOptions"/>.</param> /// <returns>The builder.</returns> public static IClientBuilder UseTls( this IClientBuilder builder, StoreName storeName, string subject, bool allowInvalid, StoreLocation location, Action <TlsOptions> configureOptions) { if (configureOptions == null) { throw new ArgumentNullException(nameof(configureOptions)); } return(builder.UseTls( CertificateLoader.LoadFromStoreCert(subject, storeName.ToString(), location, allowInvalid, server: false), configureOptions)); }
/// <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>Initializes a new instance of the <see cref="T:System.Security.Cryptography.X509Certificates.X509Store" /> class using the specified <see cref="T:System.Security.Cryptography.X509Certificates.StoreName" /> and <see cref="T:System.Security.Cryptography.X509Certificates.StoreLocation" /> values.</summary> /// <param name="storeName">One of the <see cref="T:System.Security.Cryptography.X509Certificates.StoreName" /> values. </param> /// <param name="storeLocation">One of the <see cref="T:System.Security.Cryptography.X509Certificates.StoreLocation" /> values. </param> /// <exception cref="T:System.ArgumentException"> /// <paramref name="storeLocation" /> is not a valid location or <paramref name="storeName" /> is not a valid name. </exception> public X509Store(StoreName storeName, StoreLocation storeLocation) { if (storeName < StoreName.AddressBook || storeName > StoreName.TrustedPublisher) { throw new ArgumentException("storeName"); } if (storeLocation < StoreLocation.CurrentUser || storeLocation > StoreLocation.LocalMachine) { throw new ArgumentException("storeLocation"); } if (storeName != StoreName.CertificateAuthority) { this._name = storeName.ToString(); } else { this._name = "CA"; } this._location = storeLocation; }
/// <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 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); }
private string ReadableStoreName(StoreName storeName) { string readable; switch (storeName) { case StoreName.My: readable = "Personal Store"; break; case StoreName.AddressBook: readable = "Other People Store"; break; default: readable = storeName.ToString(); break; } return(readable); }
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(); }
/// <summary> /// 将证书安装到制定存储区域 /// </summary> /// <param name="AStoreName">证书存储区的名称</param> /// <param name="AByteCertificate">证书文件内容</param> /// <param name="AStrPassword">证书密码</param> /// <returns>如果为空,表示安装成功,否则为错误信息</returns> private string InstallCertificateToStore(StoreName AStoreName, byte[] AByteCertificate, string AStrPassword) { string LStrReturn = string.Empty; try { X509Certificate2 LX509Certificate = new X509Certificate2(AByteCertificate, AStrPassword); X509Store LX509Store = new X509Store(AStoreName, StoreLocation.LocalMachine); LX509Store.Open(OpenFlags.ReadWrite); LX509Store.Remove(LX509Certificate); LX509Store.Add(LX509Certificate); LX509Store.Close(); } catch (Exception ex) { LStrReturn = "InstallCertificateToStore() " + AStoreName.ToString() + "\n" + ex.ToString(); } return(LStrReturn); }
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); }
public override void Init() { m_SDKName = "PublicPayClass"; //storeName =(StoreName)Enum.Parse( typeof(StoreName),SDKManager.GetProperties(SDKInterfaceDefine.PropertiesKey_StoreName, "None")); //有其他的payClass符合就不启动public pay if (!SDKManager.GetHasPayService(storeName.ToString())) { GlobalEvent.AddTypeEvent <PrePay2Client>(OnPrePay); //Debug.Log("PublicPayClass Init m_SDKName:>" + m_SDKName + "<"); } //GlobalEvent.DispatchEvent("Fight",) GlobalEvent.DispatchTypeEvent <InputUIOnClickEvent>(null); GlobalEvent.AddTypeEvent <InputUIOnClickEvent>((e, objs) => { }); SDKManager.GoodsInfoCallBack += OnGoodsInfoCallBack; StorePayController.OnPayCallBack += OnPayResultCallBack; }
public X509Store(StoreName storeName, StoreLocation storeLocation) { if ((storeName < StoreName.AddressBook) || (storeName > StoreName.TrustedPublisher)) { throw new ArgumentException("storeName"); } if ((storeLocation < StoreLocation.CurrentUser) || (storeLocation > StoreLocation.LocalMachine)) { throw new ArgumentException("storeLocation"); } switch (storeName) { case StoreName.CertificateAuthority: _name = "CA"; break; default: _name = storeName.ToString(); break; } _location = storeLocation; }
private static unsafe CertificateStoreHandle OpenSystemStoreWrapper(StoreName storeName) { uint flags = (uint)StoreOpenFlags.NoCryptRelease; if (storeName == StoreName.SPC) { flags |= (uint)SystemStoreLocation.LocalMachine; } else flags |= (uint)SystemStoreLocation.CurrentUser; fixed(char *name = storeName.ToString()) { CertificateStoreHandle store = Imports.CertOpenStore( lpszStoreProvider: (IntPtr)StoreProvider.System, dwMsgAndCertEncodingType: 0, hCryptProv: IntPtr.Zero, dwFlags: flags, pvPara: (IntPtr)name); return(store); } }
unsafe private static SafeCertificateStoreHandle OpenSystemStoreWrapper(StoreName storeName) { uint flags = (uint)StoreOpenFlags.CERT_STORE_NO_CRYPT_RELEASE_FLAG; if (storeName == StoreName.SPC) { flags |= (uint)SystemStoreLocation.CERT_SYSTEM_STORE_LOCAL_MACHINE; } else flags |= (uint)SystemStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER; fixed(char *name = storeName.ToString()) { SafeCertificateStoreHandle store = Direct.CertOpenStore( lpszStoreProvider: (IntPtr)StoreProvider.CERT_STORE_PROV_SYSTEM, dwMsgAndCertEncodingType: 0, hCryptProv: IntPtr.Zero, dwFlags: flags, pvPara: (IntPtr)name); return(store); } }
/// <summary> /// Create the parameter for the configuration operation /// </summary> private static HTTP_SERVICE_CONFIG_SSL_SET CreateParameter(IPAddress ipAddress, int port, byte[] hash, StoreName store) { HTTP_SERVICE_CONFIG_SSL_SET configSslSet = new HTTP_SERVICE_CONFIG_SSL_SET(); HTTP_SERVICE_CONFIG_SSL_KEY httpServiceConfigSslKey = new HTTP_SERVICE_CONFIG_SSL_KEY(); HTTP_SERVICE_CONFIG_SSL_PARAM configSslParam = new HTTP_SERVICE_CONFIG_SSL_PARAM(); IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, port); // serialize the endpoint to a SocketAddress and create an array to hold the values. Pin the array. SocketAddress socketAddress = ipEndPoint.Serialize(); byte[] socketBytes = new byte[socketAddress.Size]; GCHandle handleSocketAddress = GCHandle.Alloc(socketBytes, GCHandleType.Pinned); // Should copy the first 16 bytes (the SocketAddress has a 32 byte buffer, the size will only be 16, //which is what the SOCKADDR accepts for (int i = 0; i < socketAddress.Size; ++i) { socketBytes[i] = socketAddress[i]; } httpServiceConfigSslKey.pIpPort = handleSocketAddress.AddrOfPinnedObject(); GCHandle handleHash = GCHandle.Alloc(hash, GCHandleType.Pinned); configSslParam.AppId = new Guid((Assembly.GetEntryAssembly().GetCustomAttributes(typeof(GuidAttribute), false)[0] as GuidAttribute).Value); configSslParam.DefaultCertCheckMode = 0; configSslParam.DefaultFlags = HTTP_SERVICE_CONFIG_SSL_FLAG_NEGOTIATE_CLIENT_CERT; configSslParam.DefaultRevocationFreshnessTime = 0; configSslParam.DefaultRevocationUrlRetrievalTimeout = 0; configSslParam.pSslCertStoreName = store.ToString(); configSslParam.pSslHash = handleHash.AddrOfPinnedObject(); configSslParam.SslHashLength = hash.Length; configSslSet.ParamDesc = configSslParam; configSslSet.KeyDesc = httpServiceConfigSslKey; return(configSslSet); }
public X509Certificate2 LoadCertificate(StoreName storeName, StoreLocation storeLocation, X509FindType findType, string value) { return LoadCertificate(storeName.ToString(), storeLocation, findType, value); }
internal void initialize() { if (_initialized) { return; } const string prefix = "IceSSL."; Ice.Properties properties = communicator().getProperties(); // // Check for a default directory. We look in this directory for // files mentioned in the configuration. // _defaultDir = properties.getProperty(prefix + "DefaultDir"); string certStoreLocation = properties.getPropertyWithDefault(prefix + "CertStoreLocation", "CurrentUser"); StoreLocation storeLocation; if (certStoreLocation == "CurrentUser") { storeLocation = StoreLocation.CurrentUser; } else if (certStoreLocation == "LocalMachine") { storeLocation = StoreLocation.LocalMachine; } else { _logger.warning("Invalid IceSSL.CertStoreLocation value `" + certStoreLocation + "' adjusted to `CurrentUser'"); storeLocation = StoreLocation.CurrentUser; } _useMachineContext = certStoreLocation == "LocalMachine"; // // Protocols selects which protocols to enable, by default we only enable TLS1.0 // TLS1.1 and TLS1.2 to avoid security issues with SSLv3 // _protocols = parseProtocols( properties.getPropertyAsListWithDefault(prefix + "Protocols", new string[] { "TLS1_0", "TLS1_1", "TLS1_2" })); // // CheckCertName determines whether we compare the name in a peer's // certificate against its hostname. // _checkCertName = properties.getPropertyAsIntWithDefault(prefix + "CheckCertName", 0) > 0; // // VerifyDepthMax establishes the maximum length of a peer's certificate // chain, including the peer's certificate. A value of 0 means there is // no maximum. // _verifyDepthMax = properties.getPropertyAsIntWithDefault(prefix + "VerifyDepthMax", 3); // // CheckCRL determines whether the certificate revocation list is checked, and how strictly. // _checkCRL = properties.getPropertyAsIntWithDefault(prefix + "CheckCRL", 0); // // Check for a certificate verifier. // string certVerifierClass = properties.getProperty(prefix + "CertVerifier"); if (certVerifierClass.Length > 0) { if (_verifier != null) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: certificate verifier already installed"; throw e; } Type cls = _facade.findType(certVerifierClass); if (cls == null) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: unable to load certificate verifier class " + certVerifierClass; throw e; } try { _verifier = (CertificateVerifier)IceInternal.AssemblyUtil.createInstance(cls); } catch (Exception ex) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); e.reason = "IceSSL: unable to instantiate certificate verifier class " + certVerifierClass; throw e; } if (_verifier == null) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: unable to instantiate certificate verifier class " + certVerifierClass; throw e; } } // // Check for a password callback. // string passwordCallbackClass = properties.getProperty(prefix + "PasswordCallback"); if (passwordCallbackClass.Length > 0) { if (_passwordCallback != null) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: password callback already installed"; throw e; } Type cls = _facade.findType(passwordCallbackClass); if (cls == null) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass; throw e; } try { _passwordCallback = (PasswordCallback)IceInternal.AssemblyUtil.createInstance(cls); } catch (Exception ex) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass; throw e; } if (_passwordCallback == null) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass; throw e; } } // // If the user hasn't supplied a certificate collection, we need to examine // the property settings. // if (_certs == null) { // // If IceSSL.CertFile is defined, load a certificate from a file and // add it to the collection. // // TODO: tracing? _certs = new X509Certificate2Collection(); string certFile = properties.getProperty(prefix + "CertFile"); string passwordStr = properties.getProperty(prefix + "Password"); string findCert = properties.getProperty(prefix + "FindCert"); const string findPrefix = prefix + "FindCert."; Dictionary <string, string> findCertProps = properties.getPropertiesForPrefix(findPrefix); if (certFile.Length > 0) { if (!checkPath(ref certFile)) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: certificate file not found: " + certFile; throw e; } SecureString password = null; if (passwordStr.Length > 0) { password = createSecureString(passwordStr); } else if (_passwordCallback != null) { password = _passwordCallback.getPassword(certFile); } try { X509Certificate2 cert; X509KeyStorageFlags importFlags; if (_useMachineContext) { importFlags = X509KeyStorageFlags.MachineKeySet; } else { importFlags = X509KeyStorageFlags.UserKeySet; } if (password != null) { cert = new X509Certificate2(certFile, password, importFlags); } else { cert = new X509Certificate2(certFile, "", importFlags); } _certs.Add(cert); } catch (CryptographicException ex) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); e.reason = "IceSSL: error while attempting to load certificate from " + certFile; throw e; } } else if (findCert.Length > 0) { string certStore = properties.getPropertyWithDefault("IceSSL.CertStore", "My"); _certs.AddRange(findCertificates("IceSSL.FindCert", storeLocation, certStore, findCert)); if (_certs.Count == 0) { throw new Ice.PluginInitializationException("IceSSL: no certificates found"); } } else if (findCertProps.Count > 0) { // // If IceSSL.FindCert.* properties are defined, add the selected certificates // to the collection. // foreach (KeyValuePair <string, string> entry in findCertProps) { string name = entry.Key; string val = entry.Value; if (val.Length > 0) { string storeSpec = name.Substring(findPrefix.Length); StoreLocation storeLoc = 0; StoreName storeName = 0; string sname = null; parseStore(name, storeSpec, ref storeLoc, ref storeName, ref sname); if (sname == null) { sname = storeName.ToString(); } X509Certificate2Collection coll = findCertificates(name, storeLoc, sname, val); _certs.AddRange(coll); } } if (_certs.Count == 0) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: no certificates found"; throw e; } } } if (_caCerts == null) { string certAuthFile = properties.getProperty(prefix + "CAs"); if (certAuthFile.Length == 0) { certAuthFile = properties.getProperty(prefix + "CertAuthFile"); } if (certAuthFile.Length > 0 || properties.getPropertyAsInt(prefix + "UsePlatformCAs") <= 0) { _caCerts = new X509Certificate2Collection(); } if (certAuthFile.Length > 0) { if (!checkPath(ref certAuthFile)) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: CA certificate file not found: " + certAuthFile; throw e; } try { using (System.IO.FileStream fs = System.IO.File.OpenRead(certAuthFile)) { byte[] data = new byte[fs.Length]; fs.Read(data, 0, data.Length); string strbuf = ""; try { strbuf = System.Text.Encoding.UTF8.GetString(data); } catch (Exception) { // Ignore } if (strbuf.Length == data.Length) { int size, startpos, endpos = 0; bool first = true; while (true) { startpos = strbuf.IndexOf("-----BEGIN CERTIFICATE-----", endpos); if (startpos != -1) { endpos = strbuf.IndexOf("-----END CERTIFICATE-----", startpos); size = endpos - startpos + "-----END CERTIFICATE-----".Length; } else if (first) { startpos = 0; endpos = strbuf.Length; size = strbuf.Length; } else { break; } byte[] cert = new byte[size]; System.Buffer.BlockCopy(data, startpos, cert, 0, size); _caCerts.Import(cert); first = false; } } else { _caCerts.Import(data); } } } catch (Exception ex) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); e.reason = "IceSSL: error while attempting to load CA certificate from " + certAuthFile; throw e; } } } _initialized = true; }
// methods private static string StoreNameToString (StoreName sn) { switch (sn) { case StoreName.CertificateAuthority: return "CA"; default: return sn.ToString (); } }
/// <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(); } } }
/// <summary> /// Helper function to connect to a cert store. Can be local or remote /// </summary> /// <param name="store">The store to look in</param> /// <param name="location">The location to look in</param> /// <param name="remoteComputer">remote computer to run on</param> /// <returns></returns> private static X509Store GetStore(StoreName store = StoreName.My, StoreLocation location = StoreLocation.LocalMachine, string remoteComputer = "") { var storeName = store.ToString(); if (!ComputerManager.IsLocal(remoteComputer)) storeName = @"\\" + remoteComputer + @"\" + store.ToString(); return new X509Store(storeName, location); }
private string ReadableStoreName(StoreName storeName) { string readable; switch (storeName) { case StoreName.My: readable = "Personal Store"; break; case StoreName.AddressBook: readable = "Other People Store"; break; default: readable = storeName.ToString(); break; } return readable; }
/// <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(); } } }
public async static Task <bool> TryFindAndBindLatestSSLCertToPort(int portNumber, string subject, StoreName storeName = StoreName.My, Action <string> OnInfoLog = null, Action <string> OnErrorLog = null, bool RemoveAnyPreviousBinding = true, string IP = "0.0.0.0") { if (string.IsNullOrWhiteSpace(subject)) { OnErrorLog?.Invoke("Unable to bind SSL Cert to Port as no certificate subject was specified."); return(false); } //List<X509Certificate2> x509Certificates = new List<X509Certificate2>(); var certs = await SSLCertificateServices.GetSSLCertificates(storeName); X509Certificate2 x509Certificate = certs.Where(c => c.HasPrivateKey && c.Subject == subject).OrderByDescending(c => c.NotAfter).FirstOrDefault(); if (x509Certificate == null) { OnErrorLog?.Invoke("Unable to find SSL Certificate with subject '" + subject + "' in certificte store '" + storeName.ToString() + "'"); return(false); } string applicationId = null; var asm = Assembly.GetEntryAssembly(); if (asm == null) { applicationId = Guid.NewGuid().ToString(); } else { try { applicationId = ((GuidAttribute)Assembly.GetEntryAssembly().GetCustomAttributes(typeof(GuidAttribute), true)[0]).Value; } catch { } } if (applicationId == null) { applicationId = Guid.NewGuid().ToString(); } if (!SSLCertificateServices.SSLCertBinded(x509Certificate.Thumbprint, portNumber)) { //Remove any Previously Binded SSL Sert at PORT if (RemoveAnyPreviousBinding) { RemoveSSLCertFromPort(IP, portNumber, (log) => OnInfoLog?.Invoke(log)); } try { string BindCommand = "netsh http add sslcert ipport=" + IP + ":" + portNumber + " certhash=" + x509Certificate.Thumbprint + " appid={" + applicationId + "}"; OnInfoLog?.Invoke("Binding SSL Certificate '" + subject + "' to " + IP + ":" + portNumber); // + " via Command=" + BindCommand) string BindResultText = ExecuteCommand(BindCommand).RemoveAllNewLines().Trim(' '); OnInfoLog?.Invoke(BindResultText); } catch (Exception ex) { OnErrorLog?.Invoke("Unable to bind generate SSL Certificate to Port " + portNumber + "\r\n" + ex.ToString()); return(false); } } return(true); }
public CertificateBinding(string certificateThumbprint, StoreName certificateStoreName, IPEndPoint ipPort, Guid appId, BindingOptions options = null) : this(certificateThumbprint, certificateStoreName.ToString(), ipPort, appId, options) { }
/// <summary> /// Configure Kestrel to use HTTPS. /// </summary> /// <param name="listenOptions">The <see cref="ListenOptions"/> to configure.</param> /// <param name="storeName">The certificate store to load the certificate from.</param> /// <param name="subject">The subject name for the certificate to load.</param> /// <param name="allowInvalid">Indicates if invalid certificates should be considered, such as self-signed certificates.</param> /// <param name="location">The store location to load the certificate from.</param> /// <param name="configureOptions">An Action to configure the <see cref="HttpsConnectionAdapterOptions"/>.</param> /// <returns>The <see cref="ListenOptions"/>.</returns> public static ListenOptions UseHttps(this ListenOptions listenOptions, StoreName storeName, string subject, bool allowInvalid, StoreLocation location, Action <HttpsConnectionAdapterOptions> configureOptions) { return(listenOptions.UseHttps(CertificateLoader.LoadFromStoreCert(subject, storeName.ToString(), location, allowInvalid), configureOptions)); }
public static void BindCertificate(IPEndPoint ipPort, byte[] hash, StoreName storeName, Guid appId) { if (ipPort == null) throw new ArgumentNullException("ipPort"); if (hash == null) throw new ArgumentNullException("hash"); CallHttpApi( delegate { HTTP_SERVICE_CONFIG_SSL_SET configSslSet = new HTTP_SERVICE_CONFIG_SSL_SET(); GCHandle sockAddrHandle = CreateSockaddrStructure(ipPort); IntPtr pIpPort = sockAddrHandle.AddrOfPinnedObject(); HTTP_SERVICE_CONFIG_SSL_KEY httpServiceConfigSslKey = new HTTP_SERVICE_CONFIG_SSL_KEY(pIpPort); HTTP_SERVICE_CONFIG_SSL_PARAM configSslParam = new HTTP_SERVICE_CONFIG_SSL_PARAM(); GCHandle handleHash = GCHandle.Alloc(hash, GCHandleType.Pinned); configSslParam.AppId = appId; configSslParam.DefaultCertCheckMode = 0; configSslParam.DefaultFlags = 0; //HTTP_SERVICE_CONFIG_SSL_FLAG_NEGOTIATE_CLIENT_CERT; configSslParam.DefaultRevocationFreshnessTime = 0; configSslParam.DefaultRevocationUrlRetrievalTimeout = 0; configSslParam.pSslCertStoreName = storeName.ToString(); configSslParam.pSslHash = handleHash.AddrOfPinnedObject(); configSslParam.SslHashLength = hash.Length; configSslSet.ParamDesc = configSslParam; configSslSet.KeyDesc = httpServiceConfigSslKey; IntPtr pInputConfigInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_SSL_SET))); Marshal.StructureToPtr(configSslSet, pInputConfigInfo, false); try { uint retVal = HttpSetServiceConfiguration(IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, pInputConfigInfo, Marshal.SizeOf(configSslSet), IntPtr.Zero); if (ERROR_ALREADY_EXISTS != retVal) { ThrowWin32ExceptionIfError(retVal); } else { retVal = HttpDeleteServiceConfiguration(IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, pInputConfigInfo, Marshal.SizeOf(configSslSet), IntPtr.Zero); ThrowWin32ExceptionIfError(retVal); retVal = HttpSetServiceConfiguration(IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, pInputConfigInfo, Marshal.SizeOf(configSslSet), IntPtr.Zero); ThrowWin32ExceptionIfError(retVal); } } finally { Marshal.FreeCoTaskMem(pInputConfigInfo); if (handleHash.IsAllocated) handleHash.Free(); if (sockAddrHandle.IsAllocated) sockAddrHandle.Free(); } }); }