Add() public method

public Add ( System certificate ) : void
certificate System
return void
コード例 #1
0
ファイル: Config.cs プロジェクト: svn2github/etee
        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();
            }
        }
コード例 #2
0
ファイル: ServiceTest.cs プロジェクト: punitganshani/KonfDB
        private void AddCertificate()
        {
            var store = new X509Store(_storeName, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadWrite);
            store.Add(new X509Certificate2("RootTrustedCA.cer"));


            var certificate = new X509Certificate2("Server.cer");
            store.Add(certificate);
            _certificateThumbprint = certificate.Thumbprint;

            _certificateConfiguration = new CertificateConfiguration
            {
                FindBy = X509FindType.FindByThumbprint,
                StoreLocation = StoreLocation.LocalMachine,
                StoreName = _storeName,
                Value = _certificateThumbprint
            };

            try
            {
                // Required for server to successfully pick up the certificate
                _certificateConfiguration.BindCertificateToPort("6661");
                _certificateConfiguration.BindCertificateToPort("6671");
                _certificateConfiguration.BindCertificateToPort("6681");
            }
            catch
            {
            }
            store.Close();
        }
コード例 #3
0
        private void InstallCertificate(StoreName storeName, StoreLocation storeLocation)
        {
            Trace.TraceInformation("Creating store object for '{1}', '{0}'.", storeName, storeLocation);
            var store = new X509Store(storeName, storeLocation);
            store.Open(OpenFlags.ReadWrite);
            try
            {
                X509Certificate2Collection result = store.Certificates.Find(
                    X509FindType.FindByThumbprint, _cert.Thumbprint, false);

                if (result.Count > 0)
                {
                    Trace.TraceWarning("Certificate with thumbprint '{0}', name '{1}' already in store.",
                        _cert.Thumbprint, _cert.Subject);
                }
                else
                {
                    store.Add(_cert);
                    Trace.TraceInformation("Certificate successfully added to the store.");
                }
            }
            finally
            {
                store.Close();
            }
        }
コード例 #4
0
        /// <summary>
        /// Install a certificate to local machine store
        /// </summary>
        /// <param name="certificateFilePath"></param>
        /// <returns>Certificate added to the store.</returns>
        public static X509Certificate2 RegisterCertificate(string certificateFilePath)
        {
            // STEP 1: install the certificate to Local Machine store
            if (!File.Exists(certificateFilePath))
            {
                throw new ArgumentException("Certificate file doesn't exist.");
            }

            var certificate = new X509Certificate2(
                certificateFilePath, "1234", X509KeyStorageFlags.MachineKeySet);

            var store = new X509Store(StoreLocation.LocalMachine);

            try
            {
                store.Open(OpenFlags.ReadWrite);
                var results = store.Certificates.Find(X509FindType.FindBySerialNumber, certificate.SerialNumber, true);
                if (results.Count == 0)
                {
                    store.Add(certificate);
                }
            }
            finally
            {
                store.Close();
            }

            return certificate;
        }
コード例 #5
0
ファイル: WxHbPayAPI.cs プロジェクト: Cold1986/MZZ
        /// <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;
            }
        }
コード例 #6
0
 private static void AddCertToStore(X509Certificate2 certificate, X509Store store)
 {
     store.Open(OpenFlags.ReadWrite);
     store.Add(certificate);
     store.Close();
     Console.WriteLine("Certificate installed in store.");
 }
コード例 #7
0
ファイル: move_cert.cs プロジェクト: girish66/Oak
        static void Main(string[] args)
        {
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            var root = new X509Store(StoreName.Root, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadWrite);
            root.Open(OpenFlags.ReadWrite);

            dynamic myCert = null;

            var certificates = store.Certificates;
            foreach (var certificate in certificates)
            {
                if(certificate.IssuerName.Name == "CN=" + args[0])
                {
                    myCert = certificate;
                    break;
                }
            }

            store.Remove(myCert);
            root.Add(myCert);
            store.Close();
            root.Close();
        }
コード例 #8
0
ファイル: CustomAction.cs プロジェクト: uw-it-cte/fog-client
        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;
            }
        }
コード例 #9
0
        private void InstallWindows(MS509.X509Certificate2 cert)
        {
            var store = new MS509.X509Store(MS509.StoreName.My, MS509.StoreLocation.CurrentUser);

            store.Open(MS509.OpenFlags.ReadWrite);
            store.Add(cert);
        }
コード例 #10
0
        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;
        }
コード例 #11
0
        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);
            }
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: rkuschel/win-installer
        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 { }

            }
        }
コード例 #13
0
        /*
         * /// <summary>
         * /// Create a key pair
         * /// </summary>
         * /// <param name="pkSize">Key size</param>
         * /// <param name="pkAlgo">Key algorithm</param>
         * /// <param name="name">Key container name</param>
         * /// <returns></returns>
         * internal static CspParameters Create(int pkSize, string pkAlgo, string name)
         * {
         *  // Normalise the name
         *  string _name = name.Replace(' ', '_');
         *
         *  CspParameters cp = null;
         *  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(pkSize, cp))
         *          {
         *              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;
         *          DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(pkSize, cp);
         *          dsa.PersistKeyInCsp = true;
         *          break;
         *      //case "ECDSA":
         *          //ECKeyPairGenerator ecGenerator = new ECKeyPairGenerator(pkAlgo);
         *          //ecGenerator.Init(genParam);
         *          //keyPair = ecGenerator.GenerateKeyPair();
         *          //break;
         *      default:
         *          throw new ArgumentException("Algorithm not supported", pkAlgo);
         *  }
         *  return cp;
         * }
         */
        #endregion


        //internal static X509Certificate storeKey(CspParameters cp, X509Certificate cert)
        internal static X509Certificate storeKey(X509Certificate cert)
        {
            //SysX509.X509KeyStorageFlags keyFlags = (SysX509.X509KeyStorageFlags.UserKeySet | SysX509.X509KeyStorageFlags.Exportable);
            //SysX509.X509KeyStorageFlags keyFlags = SysX509.X509KeyStorageFlags.Exportable;

            Sys.X509Certificate2 sCert = new Sys.X509Certificate2(cert.GetEncoded());

            Sys.X509Store store = new Sys.X509Store(Sys.StoreName.My,
                                                    Sys.StoreLocation.CurrentUser);
            store.Open(Sys.OpenFlags.MaxAllowed);
            store.Add(sCert);

            Sys.X509Certificate2Collection coll = store.Certificates.Find(Sys.X509FindType.FindBySerialNumber, sCert.SerialNumber, false);

            if (coll.Count > 1)
            {
                throw new CryptoException("Too many certs");
            }

            if (coll.Count < 1)
            {
                throw new CryptoException("Cert not found");
            }

            sCert = coll[0];
            if (!sCert.HasPrivateKey)
            {
                throw new CryptoException("No private key");
            }



            return(cert);
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: kostaslamda/win-installer
        static void addcertificates(string installdir)
        {
            if (File.Exists(installdir + "\\citrixsha1.cer"))
            {
                X509Certificate2 citrix1 = new X509Certificate2(installdir + "\\citrixsha1.cer");
                X509Certificate2 citrix256 = new X509Certificate2(installdir + "\\citrixsha256.cer");
                X509Store store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);
                store.Add(citrix1);
                store.Close();
                store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);
                store.Add(citrix256);
                store.Close();
                try
                {
                    EventLog.WriteEntry(esource, "InstallGui Install Helpers Added");
                }
                catch { }
            }
            else
            {
                try
                {
                    EventLog.WriteEntry(esource, "InstallGui Install Helpers Not Needed");
                }
                catch { }

            }
        }
コード例 #15
0
ファイル: CodeSigning.cs プロジェクト: ErwinT6/T6Engine
		/// <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;
		}
コード例 #16
0
ファイル: CertificateManager.cs プロジェクト: dmetzgar/wcf
        // Adds the given certificate to the given store unless it is
        // already present.  Returns 'true' if the certificate was added.
        private static bool AddToStoreIfNeeded(StoreName storeName, 
                                               StoreLocation storeLocation, 
                                               X509Certificate2 certificate)
        {
            X509Store store = null;
            X509Certificate2 existingCert = null;
            try
            {
                store = new X509Store(storeName, storeLocation);
                store.Open(OpenFlags.ReadWrite);
                existingCert = CertificateFromThumbprint(store, certificate.Thumbprint);
                if (existingCert == null)
                {
                    store.Add(certificate);
                    Console.WriteLine("Added to store '{0}', location '{1}', certificate '{2}'", 
                                       storeName, storeLocation, certificate.SubjectName.Name);
                }

            }
            finally
            {
                if (store != null)
                {
                    store.Close();
                }
            }

            return existingCert == null;
        }
コード例 #17
0
        static SamlFubuApplication()
        {
            var location = AppDomain.CurrentDomain.BaseDirectory;

            var certPath = location.AppendPath("cert2.pfx");

            if (!File.Exists(certPath))
            {
                throw new InvalidOperationException("Couldn't find path " + certPath);
            }

            var cert = new X509Certificate2(certPath, new SecureString(), X509KeyStorageFlags.Exportable);
            Certificate = new X509Certificate2(cert);

            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadWrite);
            store.Add(Certificate);
            

            SamlCertificate = new SamlCertificate
            {
                Issuer = "fake:saml:issuer",
                CertificateIssuer = Certificate.Issuer,
                SerialNumber = Certificate.SerialNumber,
                Thumbprint = Certificate.Thumbprint
            };
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: qanuj/servant
        public static void InstallServantCertificate()
        {
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadWrite);

            //CRASH!
                // Servant certifikatet kan ikke bindes til Azure serveren, ved mindre det bliver eksporteret og importeret først. Den siger det der med local user blablal..

            X509Certificate2 cert;
            using (var ctx = new CryptContext())
            {
                ctx.Open();
                cert = ctx.CreateSelfSignedCertificate(
                    new SelfSignedCertProperties
                    {
                        IsPrivateKeyExportable = true,
                        KeyBitLength = 4096,
                        Name = new X500DistinguishedName("CN=\"Servant\"; C=\"Denmark\"; O=\"Denmark\"; OU=\"Denmark\";"),
                        ValidFrom = DateTime.Today,
                        ValidTo = DateTime.Today.AddYears(10)
                    });
            }
            cert.FriendlyName = "Servant";
            store.Add(cert);
            store.Close();

            System.Threading.Thread.Sleep(1000); // Wait for certificate to be installed
        }
コード例 #19
0
ファイル: CertificateManager.cs プロジェクト: Richard-FF/wcf
        // Adds the given certificate to the given store unless it is
        // already present.  Returns 'true' if the certificate was added.
        private static bool AddToStoreIfNeeded(StoreName storeName,
                                               StoreLocation storeLocation,
                                               X509Certificate2 certificate)
        {
            X509Store store = null;
            X509Certificate2 existingCert = null;
            try
            {
                store = new X509Store(storeName, storeLocation);

                // We assume Bridge is running elevated
                store.Open(OpenFlags.ReadWrite);
                existingCert = CertificateFromThumbprint(store, certificate.Thumbprint);
                if (existingCert == null)
                {
                    store.Add(certificate);
                    Trace.WriteLine(string.Format("[CertificateManager] Added certificate to store: "));
                    Trace.WriteLine(string.Format("    {0} = {1}", "StoreName", storeName));
                    Trace.WriteLine(string.Format("    {0} = {1}", "StoreLocation", storeLocation));
                    Trace.WriteLine(string.Format("    {0} = {1}", "CN", certificate.SubjectName.Name));
                    Trace.WriteLine(string.Format("    {0} = {1}", "HasPrivateKey", certificate.HasPrivateKey));
                    Trace.WriteLine(string.Format("    {0} = {1}", "Thumbprint", certificate.Thumbprint));
                }

            }
            finally
            {
                if (store != null)
                {
                    store.Close();
                }
            }

            return existingCert == null;
        }
コード例 #20
0
        public void Execute(object parameter)
        {
            var pfx = CertificateManager.GeneratePfx(CertificateName, CertificatePassword);
            var certificate = CertificateManager.GetCertificateForBytes(pfx.GetBytes(), CertificatePassword);

            File.WriteAllBytes(Path.Combine(AppHelper.CachePath, "AzureAutomation.pfx"), pfx.GetBytes());
            File.WriteAllBytes(Path.Combine(AppHelper.CachePath, "AzureAutomation.cer"), certificate);

            var collection = new X509Certificate2Collection();
            collection.Import(Path.Combine(AppHelper.CachePath, "AzureAutomation.pfx"), CertificatePassword, X509KeyStorageFlags.PersistKeySet);

            var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadWrite);

            // Store the certificate
            foreach (var cert in collection)
                store.Add(cert);

            store.Close();

            // Delete the certificate that contains the private key - this is already imported into the cert store
            File.Delete(Path.Combine(AppHelper.CachePath, "AzureAutomation.pfx"));

            MessageBox.Show("The certificate has been generated. Please refresh the certificates list.", "Certificate", MessageBoxButton.OK);

            // Open the folder containing the certificate
            Process.Start("explorer.exe", AppHelper.CachePath);
        }
コード例 #21
0
        /// <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();
                }
            }
        }
コード例 #22
0
ファイル: Certificate.cs プロジェクト: turbonaitis/stubby4net
        public static bool AddCertificateToStore(uint httpsPort)
        {
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            try {
                store.Open(OpenFlags.ReadWrite);
            } catch {
                Out.Error(AuthenticationNeeded);
                return false;
            }

            var cert = new X509Certificate2(
                CreateSelfSignCertificatePfx(X509SubjectName, DateTime.Now.AddDays(-1), DateTime.Now.AddYears(1), CertificatePassword),
                CertificatePassword,
                X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
            cert.FriendlyName = "Stubby4net Certificate";

            var existingCerts = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.Subject, false);
            if(existingCerts.Count == 0)
                store.Add(cert);
            else
                cert = existingCerts[0];
            store.Close();

            var netshArgs = String.Format(NetshArgs, httpsPort, cert.GetCertHashString(), "{" + Stubby.Guid + "}");
            var netsh = new ProcessStartInfo("netsh", netshArgs)
            {
                Verb = "runas",
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden,
                UseShellExecute = true
            };

            try {
                var process = Process.Start(netsh);
                process.WaitForExit();
                Console.Out.WriteLine(process.ExitCode);
                if(process.ExitCode == 0)
                    return true;
            } catch {
            }

            var httpcfgArgs = String.Format(HttpcfgArgs, httpsPort, cert.GetCertHashString());
            var httpcfg = new ProcessStartInfo("httpcfg", httpcfgArgs)
            {
                Verb = "runas",
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden,
                UseShellExecute = true
            };

            try {
                var process = Process.Start(httpcfg);
                process.WaitForExit();
                return process.ExitCode == 0;
            } catch {
                return false;
            }
        }
コード例 #23
0
        public void SetUp()
        {
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadWrite);

            certificate2 = ObjectMother.Certificate2();
            store.Add(certificate2);
        }
コード例 #24
0
        static void Main(string[] args)
        {
            const string keyStore = "dataProtectionSamples";
            const string appName = "X509ProtectedFileSystemNoDI";
            const string purpose = "Demonstration";

            var programKeyStore =
                Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                    $"{keyStore}\\{appName}");
            Console.WriteLine($"Keys stored in\n{programKeyStore}");

            // Normally you'd have the certificate in the user certificate store, this is just for demo purposes.
            // Don't hardcode certificate passwords!
            // Certificate was generated with
            // makecert -r -pe -n "CN=Data Protection" -b 07/01/2015 -e 07/01/2020 -sky exchange -eku 1.3.6.1.4.1.311.10.3.12 -ss my

            var encryptingCertificate = new X509Certificate2(
                "protectionCertificate.pfx",
                "password",
                X509KeyStorageFlags.UserKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

            // You must put the cert in the store for unprotect to work. This is a limitation of the EncryptedXml class used to store the cert.
            var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadWrite);
            store.Add(encryptingCertificate);
            store.Close();

            // instantiate the data protection system at this folder
            var dataProtectionProvider = new DataProtectionProvider(new DirectoryInfo(programKeyStore),
                options =>
                    {
                        // As we're using a self signed certificate we need to provide an instance of the certificate.
                        // Thumb-print look-ups are restricted to "valid" certs (i.e. ones chained to a trusted root and which haven't expired)
                        options.ProtectKeysWithCertificate(encryptingCertificate);
                        options.SetApplicationName(appName);
                    }
                );

            var protector = dataProtectionProvider.CreateProtector(purpose);
            Console.Write("Enter input: ");
            string input = Console.ReadLine();

            // protect the payload
            string protectedPayload = protector.Protect(input);
            Console.WriteLine($"Protect returned: {protectedPayload}");

            // unprotect the payload
            string unprotectedPayload = protector.Unprotect(protectedPayload);
            Console.WriteLine($"Unprotect returned: {unprotectedPayload}");

            // Clean up certificate store.
            store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadWrite);
            store.Remove(encryptingCertificate);

            Console.ReadLine();
        }
コード例 #25
0
        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;
        }
コード例 #26
0
ファイル: Program.cs プロジェクト: nick121212/xima_desktop3
 static void InstallCertificate(StoreName storageName, byte[] certificatefile)
 {
     X509Certificate2 certificate = new X509Certificate2(certificatefile);
     X509Store store = new X509Store(storageName, StoreLocation.LocalMachine);
     store.Open(OpenFlags.ReadWrite);
     store.Remove(certificate);
     store.Add(certificate);
     store.Close();
 }
コード例 #27
0
        public void GivenPlacedIntoTheStoreForThe(string storeName, string storeLocation) {
            var store = new X509Store(storeName, ParseEnum<StoreLocation>(storeLocation));
            store.Open(OpenFlags.ReadWrite);
            store.Add(Context.Certificate);

            Context.CertificatesToCleanup.Add(Context.Certificate);
            Context.StoreName = storeName;
            Context.StoreLocation = storeLocation;
        }
コード例 #28
0
        private static void ImportCertificate(X509Certificate2 importedCert)
        {
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadWrite);

            store.Add(importedCert);
          
            store.Close();
        }
コード例 #29
0
ファイル: certOperations.cs プロジェクト: dougsland/rhevUP
        public void addPfxCertificate(string path, string password)
        {
            X509Certificate2 cert = new X509Certificate2(path, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            store.Open(OpenFlags.MaxAllowed);
            store.Add(cert);
            AddPermissionToCertificate(cert);
            store.Close();
        }
コード例 #30
0
        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();
        }
コード例 #31
0
        public X509Certificate2 InstallCertificate(Certificate certificate, X509Store store)
        {
            byte[] content = this.certificateBlobContainer.GetBytes(certificate.Id.ToString());
            var cert = new X509Certificate2(content, certificate.Password);
            store.Open(OpenFlags.ReadWrite);
            store.Add(cert);

            TraceHelper.TraceInformation("Certificate {0} installed; Friendly Name: {1}", certificate.Name, cert.FriendlyName);

            return cert;
        }
コード例 #32
0
ファイル: SSLAid.cs プロジェクト: zhangwuhua/ZwhAid4.0
 public X509Store GetX509Store()
 {
     X509Store store = new X509Store();
     try
     {
         X509Certificate2 x5092 = GetX5092();
         store.Open(OpenFlags.MaxAllowed);
         store.Add(x5092);
         store.Close();
     }
     catch { }
     return store;
 }
コード例 #33
0
ファイル: certOperations.cs プロジェクト: dougsland/rhevUP
        public void addCertificateTrustedRootCertificateAuthorities(string path)
        {
            /* Load certificate */
            X509Certificate2 cert = new X509Certificate2(path);

            /* Place to store cert */
            X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);

            /* Add cert to the store */
            store.Open(OpenFlags.ReadWrite);
            store.Add(cert);
            store.Close();
        }
コード例 #34
0
        internal static byte[] ExportToP12(CspParameters cspParam, X509Certificate cert, string password)
        {
            Sys.X509Certificate2 sysCert = new Sys.X509Certificate2(cert.GetEncoded());;

            Sys.X509Store store = new Sys.X509Store(Sys.StoreLocation.CurrentUser);
            store.Open(Sys.OpenFlags.ReadWrite);
            store.Add(sysCert);

            sysCert = store.Certificates[0];

            // Export the certificate including the private key.
            return(sysCert.Export(Sys.X509ContentType.Pkcs12, password));
        }
コード例 #35
0
 /*
  * 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();
     }
 }
コード例 #36
0
        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;
        }
コード例 #37
0
 private static void SaveToStore(X509Certificate2 cert, StoreName storeName)
 {
     X509Store x509Store = null;
     try
     {
         x509Store = new X509Store(storeName, StoreLocation.CurrentUser);
         x509Store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);
         x509Store.Add(cert);
     }
     finally
     {
         x509Store.Close();
     }
 }
コード例 #38
0
        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();
            }
        }
コード例 #39
0
        /// <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);
        }
コード例 #40
0
ファイル: Program.cs プロジェクト: coderli7/WinForm
        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;
        }
コード例 #41
0
        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);
        }
コード例 #42
0
ファイル: RemoteHook.cs プロジェクト: tloeb/carteiro_win
        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");
            }
        }
コード例 #43
0
        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); }
        }
コード例 #44
0
        /// <summary>
        /// Establishes the SSL certificate we will use for communication with
        /// RPC clients and starts a seperate thread to listen for connections
        /// </summary>
        /// <param name="port">port to listen on</param>
        /// <param name="service">The KeePassRPCService the server should interact with.</param>
        public KeePassRPCServer(int port, KeePassRPCService service, KeePassRPCExt keePassRPCPlugin, bool useSSL)
        {
            _useSSL = useSSL;
            if (keePassRPCPlugin.logger != null)
            {
                keePassRPCPlugin.logger.WriteLine("Starting KPRPCServer");
            }
            Service          = service;
            KeePassRPCPlugin = keePassRPCPlugin;

            if (_useSSL)
            {
//                if (true)
                if (Type.GetType("Mono.Runtime") == null)
                {
                    _store = new System.Security.Cryptography.X509Certificates.X509Store();
                    _store.Open(OpenFlags.ReadWrite);

                    // Find any certificates in this user's certificate store and re-use
                    // them rather than suffer the overhead of creating an entirly new
                    // certificate. Our certificates are considered "invalid" by the
                    // store (probably becuase they are self-signed)
                    X509Certificate2Collection matchingCertificates = _store.Certificates
                                                                      .Find(X509FindType.FindBySubjectDistinguishedName,
                                                                            "CN=KeePassRPC certificate for " + Environment.MachineName, false);

                    //foreach (X509Certificate2 temp in matchingCertificates)
                    //    _store.Remove(temp);

                    //matchingCertificates = _store.Certificates
                    //    .Find(X509FindType.FindBySubjectDistinguishedName,
                    //        "CN=KeePassRPC TLS aaa for " + Environment.MachineName, false);

                    if (keePassRPCPlugin.logger != null)
                    {
                        keePassRPCPlugin.logger.WriteLine("Matching certificates from store: " + matchingCertificates.Count);
                    }
                    if (matchingCertificates.Count > 0)
                    {
                        _serverCertificate = matchingCertificates[0];
                    }
                    else
                    {
                        //_serverCertificate = (X509Certificate2)X509Certificate2.CreateFromCertFile(Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "KeePassRPC"), "cert.p12"));

                        if (keePassRPCPlugin.logger != null)
                        {
                            keePassRPCPlugin.logger.WriteLine("Generating new certificate (MS).");
                        }
                        // We can use the MakeCert feature from Mono to generate a new
                        // certificate for use by this user on this machine. This means
                        // that every KeePassRPC user will establish TLS connections
                        // that are protected by a private key held on their own
                        // system, rather than a key that is disclosed in this open
                        // source code. NB: The local server is assumed to be secure!
                        PKCS12 p12  = MakeCertKPRPC.Generate("KeePassRPC certificate for " + Environment.MachineName, "KeePassRPC Automated Self-Signed Key Generator", keePassRPCPlugin);
                        byte[] cert = p12.GetBytes();
                        _serverCertificate = new X509Certificate2(cert, (string)null, X509KeyStorageFlags.PersistKeySet);
                        _store.Add(_serverCertificate);
                    }
                }
                else
                {
                    /*
                     * Problem 1:
                     *   For Linux/Mono, we cannot use the X509Store. It appears that only a .cer file is saved. That certificate does not include
                     *   the private key that we need for SSL. So we will need to save the key ourselves.
                     *
                     * Problem 2:
                     *   When using PKCS12 SaveToFile to save the key ourselves, it appears that it is not possible to save a private key that is not
                     *   password protected.
                     *
                     */
                    string certdir  = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "KeePassRPC");
                    string certfile = Path.Combine(certdir, "cert.p12");
                    _serverCertificate = null;

                    // Check if cert directory exists, if not, we need to create it
                    if (!System.IO.Directory.Exists(certdir))
                    {
                        if (keePassRPCPlugin.logger != null)
                        {
                            keePassRPCPlugin.logger.WriteLine("Cert directory does not exist, creating " + certdir);
                        }

                        System.IO.Directory.CreateDirectory(certdir);

                        if (keePassRPCPlugin.logger != null)
                        {
                            keePassRPCPlugin.logger.WriteLine("Cert directory created");
                        }
                    }
                    else
                    {
                        // Attempt to load cert
                        try {
                            if (keePassRPCPlugin.logger != null)
                            {
                                keePassRPCPlugin.logger.WriteLine("Looking for existing certificate (Mono)");
                            }
                            _serverCertificate = new X509Certificate2();
                            _serverCertificate.Import(certfile, pkcs12_password, X509KeyStorageFlags.PersistKeySet);
                            if (keePassRPCPlugin.logger != null)
                            {
                                keePassRPCPlugin.logger.WriteLine("Existing certificate loaded(Mono) : " + certfile);
                            }
                        }
                        catch (Exception ex) {
                            _serverCertificate = null;
                        }
                    }
                    // If we didn't load a cert, create one and save it
                    if (_serverCertificate == null)
                    {
                        if (keePassRPCPlugin.logger != null)
                        {
                            keePassRPCPlugin.logger.WriteLine("Generating new certificate (Mono).");
                        }

                        PKCS12 p12 = MakeCertKPRPC.Generate("KeePassRPC certificate for " + Environment.MachineName, "KeePassRPC Automated Self-Signed Key Generator", pkcs12_password, keePassRPCPlugin);
                        p12.SaveToFile(certfile);
                        byte[] cert = p12.GetBytes();
                        _serverCertificate = new X509Certificate2(cert, pkcs12_password, X509KeyStorageFlags.PersistKeySet);
                        if (keePassRPCPlugin.logger != null)
                        {
                            keePassRPCPlugin.logger.WriteLine("Generated new certificate (Mono) : " + certfile);
                        }
                    }
                }
            }

            if (keePassRPCPlugin.logger != null)
            {
                keePassRPCPlugin.logger.WriteLine("Server certificate has private key? " + _serverCertificate.HasPrivateKey);
            }

            try
            {
                this._tcpListener  = new TcpListener(IPAddress.Loopback, port);
                this._listenThread = new Thread(new ThreadStart(ListenForClients));
                this._listenThread.Start();
                this._isListening = true; // just in case the main thread checks
                // for successful startup before the thread has got going.
            }
            catch (Exception e)
            {
                if (keePassRPCPlugin.logger != null)
                {
                    keePassRPCPlugin.logger.WriteLine("Failed to start TCP listener: " + e.ToString());
                }
            }
            if (keePassRPCPlugin.logger != null)
            {
                keePassRPCPlugin.logger.WriteLine("Started KPRPCServer");
            }
        }