Inheritance: IDisposable
示例#1
0
        public static void RemoveCertificateFromLocalStoreByFriendlyName(string friendlyName, out bool removed)
        {
            removed = false;

            using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
            {
                store.Open(OpenFlags.ReadWrite | OpenFlags.IncludeArchived);

                // You could also use a more specific find type such as X509FindType.FindByThumbprint
                X509Certificate2Collection col =
                    store.Certificates;

                foreach (var cert in col)
                {
                    if (cert.FriendlyName == friendlyName)
                    {
                        store.Remove(cert);
                        TryRemovePrivateKey(cert);
                        removed = true;
                        break;
                    }
                }

                store.Close();
            }
        }
示例#2
0
 static void try_export(System.Security.Cryptography.X509Certificates.X509Store store, string pass)
 {
     foreach (X509Certificate2 certificate in store.Certificates)
     {
         Console.WriteLine("[+] Subject Name: " + certificate.Subject);
         Console.WriteLine("[+] Thumbprint  : " + certificate.Thumbprint);
         try
         {
             if (certificate.PrivateKey != null)
             {
                 Console.WriteLine("[+] Private Key : YES");
             }
             else
             {
                 Console.WriteLine("[+] Private Key : NO");
             }
             byte[] certBytes = certificate.Export(X509ContentType.Pkcs12, pass);
             Console.WriteLine(System.Convert.ToBase64String(certBytes));
             Console.WriteLine("\n");
         }
         catch
         {
             Console.WriteLine("----> COULD NOT EXPORT - NOT ADMIN OR NOT MARKED AS EXPORTABLE");
         }
     }
 }
        public static X509Certificate2 GetCertificate(string serialNumber)
        {
            List<string> list = new List<string>();
            X509Store storeCurUser = new X509Store(StoreLocation.CurrentUser);

            storeCurUser.Open(OpenFlags.ReadOnly);
            
            foreach (X509Certificate2 mCert in storeCurUser.Certificates)
            {
                if (mCert.SerialNumber.Contains(serialNumber))
                {
                    return mCert;
                }
            }

            X509Store storeMachine = new X509Store(StoreLocation.LocalMachine);

            storeMachine.Open(OpenFlags.ReadOnly);

            foreach (X509Certificate2 mCert in storeMachine.Certificates)
            {
                if (mCert.SerialNumber.Contains(serialNumber))
                {
                    return mCert;
                }
            }

            return null;
        }
示例#4
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute("Api", "{Controller}");
            config.EnableCors();

            var issuer = ConfigurationManager.AppSettings["Issuer"];
            var audience = ConfigurationManager.AppSettings["Audience"];
            var signingCertificateSubjectDistinguishedName = ConfigurationManager.AppSettings["SigningCertificateSubjectDistinguishedName"];

            var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);
            var certificate = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, signingCertificateSubjectDistinguishedName, true)[0];

            // JSON should serialize to camelCase, not PascalCase (the default)
            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            // Api controllers with an [Authorize] attribute will be validated with JWT
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences = new[] {audience},
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new X509CertificateSecurityTokenProvider(issuer, certificate),
                        //new X509CertificateSecurityTokenProvider(issuer, new X509Certificate2("PATH_TO_YOUR_PUBLIC_CERTIFICATE.cer")),
                    },
                });

            app.UseWebApi(config);
        }
示例#5
0
        public ApplePushChannel(ApplePushChannelSettings channelSettings)
        {
            cancelToken = cancelTokenSrc.Token;

            appleSettings = channelSettings;

            certificate = this.appleSettings.Certificate;

            certificates = new X509CertificateCollection();

            if (appleSettings.AddLocalAndMachineCertificateStores)
            {
                var store = new X509Store(StoreLocation.LocalMachine);
                certificates.AddRange(store.Certificates);

                store = new X509Store(StoreLocation.CurrentUser);
                certificates.AddRange(store.Certificates);
            }

            certificates.Add(certificate);

            if (this.appleSettings.AdditionalCertificates != null)
                foreach (var addlCert in this.appleSettings.AdditionalCertificates)
                    certificates.Add(addlCert);

            timerCleanup = new Timer(state => Cleanup(), null, TimeSpan.FromMilliseconds(1000), TimeSpan.FromMilliseconds(1000));
        }
        private static X509Certificate2 GetACertificateWithPrivateKeyInStore(StoreName storeName, StoreLocation storeLocation)
        {
            Trace.WriteLine(string.Format("Looking for certificates in store : {0}, store location : {1}", storeName, storeLocation));

            var certificateStore = new X509Store(storeName, storeLocation);
            certificateStore.Open(OpenFlags.ReadOnly);
            foreach (var certificate in certificateStore.Certificates)
            {
                if (certificate.HasPrivateKey && certificate.PublicKey.Key.KeySize == 2048)
                {
                    try
                    {
                        var key = certificate.PrivateKey;
                        Trace.WriteLine("Found a suitable certificate with a private key");
                        Trace.WriteLine(string.Format("Certificate issuer : {0}, Subject Name : {1}", certificate.Issuer, certificate.Subject));
                        return certificate;
                    }
                    catch (Exception)
                    {
                        Trace.WriteLine("Ignoring a Cryptography Next generation (CNG) cert");
                    }
                }
            }

            return null;
        }
示例#7
0
        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;
            }
        }
示例#8
0
        static X509Certificate2 GetCertificate(string certFindValue)
        {
            StoreLocation[] locations = new StoreLocation[] { StoreLocation.LocalMachine, StoreLocation.CurrentUser };
            foreach (StoreLocation location in locations)
            {
                X509Store store = new X509Store(StoreName.My, location);
                store.Open(OpenFlags.OpenExistingOnly);

                X509Certificate2Collection collection = store.Certificates.Find(
                    X509FindType.FindBySubjectName,
                    certFindValue,
                    false);

                if (collection.Count == 0)
                {
                    collection = store.Certificates.Find(
                        X509FindType.FindByThumbprint,
                        certFindValue,
                        false);
                }

                store.Close();

                if (collection.Count > 0)
                {
                    return collection[0];
                }
            }

            throw new ArgumentException("No certificate can be found using the find value " + certFindValue);
        }
示例#9
0
        private static string GetEncryptionCertPrivateKey()
        {
            string privateKey = string.Empty;
            X509Store store = new X509Store("MY", StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

            X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
            X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, ConfigurationManager.AppSettings["EncryptionKeyCertThumbprint"], false);

            if (fcollection.Count != 1)
            {
                throw new InvalidOperationException("Could not find the cert or more than one certs found!");
            }

            foreach (X509Certificate2 x509 in fcollection)
            {
                try
                {
                    byte[] rawdata = x509.RawData;
                    privateKey = x509.PrivateKey.ToXmlString(false);
                    x509.Reset();
                }
                catch (CryptographicException)
                {
                    throw new InvalidOperationException("Information could not be retrieved out for this certificate.");
                }
            }
            store.Close();
            return privateKey;
        }
 private static X509Certificate GetServerCertificate()
 {
     X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
     store.Open(OpenFlags.ReadOnly);
     X509CertificateCollection cert = store.Certificates.Find(X509FindType.FindBySubjectName, "LocalHost", true);
     return cert[0];
 }
示例#11
0
        public GcmXmppConnection (GcmXmppConfiguration configuration)
        {
            authCompletion = new TaskCompletionSource<bool> ();

            notifications = new Dictionary<string,CompletableNotification> ();
            Configuration = configuration;

            certificates = new X509CertificateCollection ();

            // Add local/machine certificate stores to our collection if requested
            //if (Configuration.AddLocalAndMachineCertificateStores) {
                var store = new X509Store (StoreLocation.LocalMachine);
                certificates.AddRange (store.Certificates);

                store = new X509Store (StoreLocation.CurrentUser);
                certificates.AddRange (store.Certificates);
            //}

            // Add optionally specified additional certs into our collection
//            if (Configuration.AdditionalCertificates != null) {
//                foreach (var addlCert in Configuration.AdditionalCertificates)
//                    certificates.Add (addlCert);
//            }

            // Finally, add the main private cert for authenticating to our collection
//            if (certificate != null)
//                certificates.Add (certificate);
        }
        /// <summary>
        /// Handle challenges for a secured resource by prompting for a client certificate
        /// </summary>
        public async Task<Credential> CreateCredentialAsync(CredentialRequestInfo info)
        {
            Credential credential = null;

            try
            {
                // Use the X509Store to get available certificates
                var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly);
                var certificates = store.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, true);

                // Ask the user to select a certificate to use
                certificates = X509Certificate2UI.SelectFromCollection(certificates, "Select Certificate",
                    "Select the certificate to use for authentication.", X509SelectionFlag.SingleSelection);

                // Create a new CertificateCredential using the chosen certificate
                credential = new CertificateCredential(certificates[0])
                {
                    ServiceUri = SecuredPortalUrl
                };

            }
            catch (Exception ex)
            { 
                Debug.WriteLine("Exception: " + ex.Message); 
            }

            // Return the CertificateCredential for the secured portal
            return credential;
        }
 private static X509Certificate2 selectcert() //select cert from store & set selectedcert
 {
     try
     {
         if (File.Exists("c:\\hasher.cer"))
         {
             X509Certificate2 cert = new X509Certificate2("c:\\hasher.cer");
             appLog.WriteEntry("Selected Cert: " + cert.Subject, System.Diagnostics.EventLogEntryType.Information);
             return(cert);
         }
         else
         {
             System.Security.Cryptography.X509Certificates.X509Store mystore = new System.Security.Cryptography.X509Certificates.X509Store(StoreLocation.CurrentUser);
             mystore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
             X509Certificate2Collection certCollection     = (X509Certificate2Collection)mystore.Certificates;
             X509Certificate2Collection foundCollection    = (X509Certificate2Collection)certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
             X509Certificate2Collection selectedcollection = X509Certificate2UI.SelectFromCollection(foundCollection, "Select a Certificate.", "Select a Certificate from the following list to get information on that certificate", X509SelectionFlag.SingleSelection);
             if (selectedcollection.Count > 0)
             {
                 X509Certificate2 certz = selectedcollection[0];
                 appLog.WriteEntry("Selected Cert: " + certz.Subject, System.Diagnostics.EventLogEntryType.Information);
                 return(certz);
             }
             appLog.WriteEntry("No Cert Selected", System.Diagnostics.EventLogEntryType.Warning);
             return(null);
         }
     }
     catch (Exception e)
     {
         appLog.WriteEntry(e.Message + e.StackTrace, System.Diagnostics.EventLogEntryType.Warning);
         return(null);
     }
 }
        /// <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();
                }
            }
        }
示例#15
0
        /// <summary>
        /// Gets the physical certificates that match the input certificate from the Local Machine and Trusted People store.
        /// </summary>
        /// <param name="certificate"></param>
        /// <returns></returns>
        public static List<X509Certificate2> GetCertificates(Certificate certificate)
        {
            // If the certificate is null then we have none matching ?
            if (certificate == null)
                return null;

            X509Store x509Store;

            try
            {
                x509Store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine);
                x509Store.Open(OpenFlags.ReadOnly);
            }
            catch (Exception ex)
            {
                Logger.Error("Could not access certificate store.", ex);
                return null;
            }

            return x509Store.Certificates.Cast<X509Certificate2>().Where(c => (ContainsCondition(c.Issuer, certificate.Issuer)) &&
                                                                              (EqualCondition(c.GetPublicKeyString(), certificate.PublicKey)) &&
                                                                              (EqualCondition(c.GetSerialNumberString(), certificate.SerialNumber)) &&
                                                                              (ContainsCondition(c.Subject, certificate.Subject)) &&
                                                                              (EqualCondition(c.GetEffectiveDateString(), certificate.ValidFrom != DateTime.MinValue ? certificate.ValidFrom.ToString() : null)) &&
                                                                              (EqualCondition(c.GetExpirationDateString(), certificate.ValidTo != DateTime.MinValue ? certificate.ValidTo.ToString() : null))).ToList();
        }
示例#16
0
        internal static X509Certificate Initialize(ICertificateConfig cerConfig)
        {
            if (!string.IsNullOrEmpty(cerConfig.FilePath))
            {
                //To keep compatible with website hosting
                string filePath;

                if (Path.IsPathRooted(cerConfig.FilePath))
                    filePath = cerConfig.FilePath;
                else
                {
                    filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, cerConfig.FilePath);
                }

                return new X509Certificate2(filePath, cerConfig.Password);
            }
            else
            {
                var storeName = cerConfig.StoreName;
                if (string.IsNullOrEmpty(storeName))
                    storeName = "Root";

                var store = new X509Store(storeName);

                store.Open(OpenFlags.ReadOnly);

                var cert = store.Certificates.OfType<X509Certificate2>().Where(c =>
                    c.Thumbprint.Equals(cerConfig.Thumbprint, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

                store.Close();

                return cert;
            }
        }
示例#17
0
        public static X509Store Load(string file, string password) {
            if (file == null || password == null) {
                return null;
            }

            if (!File.Exists(file)) {
                throw new FileNotFoundException("", file);
            }

            var fileContents = File.ReadAllBytes(file);
            var ptr = Marshal.AllocHGlobal(fileContents.Length);
            Marshal.Copy(fileContents, 0, ptr, fileContents.Length);
            var cryptBlob = new CRYPT_DATA_BLOB {
                cbData = (uint)fileContents.Length,
                pbData = ptr
            };
            if (!PFXIsPFXBlob(ref cryptBlob)) {
                return null;
            }
            if (!PFXVerifyPassword(ref cryptBlob, password)) {
                return null;
            }

            X509Store store = null;
            var storePtr = PFXImportCertStore(ref cryptBlob, password);
            store = new X509Store(storePtr);
            Marshal.FreeHGlobal(ptr);
            return store;
        }
示例#18
0
 /// <summary>
 /// Gets a X509 specific certificate from windows store withoit asking the user.
 /// </summary>
 /// <returns></returns>
 public static X509Certificate2 GetCertificate(StoreLocation location, string subjectName)
 {
     X509Certificate2 cert = null;
     var store = new X509Store(StoreName.My, location);
     store.Open(OpenFlags.ReadOnly);
     try
     {
         X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName,
                                            false);
         if (certs.Count == 1)
         {
             cert = certs[0];
         }
         else
         {
             cert = null;
         }
     }
     finally
     {
         if (store != null)
         {
             store.Close();
         }
     }
     return cert;
 }
示例#19
0
        private bool LoadCertificateByThumbprint(string thumbprint)
        {
            thumbprint = thumbprint.Replace(" ", "").ToUpperInvariant();
            StoreName storeName = StoreName.My;
            StoreLocation storeLocation = StoreLocation.LocalMachine;
            X509Store store = new X509Store(storeName, storeLocation);

            try
            {
                store.Open(OpenFlags.ReadOnly);

                foreach (var cert in store.Certificates)
                {
                    if (cert.HasPrivateKey == false)
                        continue;

                    if (String.Compare(cert.Thumbprint, thumbprint) == 0)
                    {
                        _certificate = cert;
                        break;
                    }
                }
            }
            finally
            {
                store.Close();
            }

            if (_certificate == null)
            {
                throw new InvalidOperationException("The certificate with the thumbprint " + thumbprint + " could not be found.");
            }

            return true;
        }
示例#20
0
        public bool OnValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
        {
            if (errors.ToString() != "None")
            {
                MessageBox.Show("Please click yes on the next dialog box.\nThis will allow us to install the Net7 certificate.", "Certificate Install",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                try
                {
                    X509Store Certificate = new X509Store(StoreName.Root);

                    X509Certificate2 cert2 = new X509Certificate2(cert);

                    Certificate.Open(OpenFlags.ReadWrite);

                    // Add Certificate
                    Certificate.Add(cert2);
                    Certificate.Close();
                }
                catch (Exception e)
                {
                    MessageBox.Show("Error installing certificate: " + e.ToString());
                }
            }
            else
            {
                MessageBox.Show("Certificate is installed!");
            }

            // Remove this message
            ServicePointManager.ServerCertificateValidationCallback = null;

            return true;
        }
示例#21
0
        private void Client()
        {

            SocketWatcher c_w = new SocketWatcher(20);
            c_w.Synchronous = true;

            // Note: must have a client cert in your IE cert store.
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);

            if (store.Certificates.Count > 0)
            {
                c_w.LocalCertificate = store.Certificates[0];
            }
            else
            {
                lock (done)
                {
                    errorMessage = "There were no certificates in the Windows Certificate Store.";
                    succeeded = false;
                    Monitor.Pulse(done);
                }

                return;
            }
            c_w.CreateConnectSocket(this, a, true, "localhost");
        }
示例#22
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);
        }
示例#23
0
        public static X509Certificate2 GetX509Certificate2(String thumbprint)
        {
            X509Certificate2 x509Certificate2 = null;

            X509Store store = new X509Store("My", StoreLocation.LocalMachine);

            try
            {
                store.Open(OpenFlags.ReadOnly);

                X509Certificate2Collection x509Certificate2Collection = store.Certificates.Find(X509FindType.FindByThumbprint,
                                                                                                thumbprint,
                                                                                                false);

                x509Certificate2 = x509Certificate2Collection[0];
            }
            catch (Exception ex)
            {
                Logger.Write(string.Format("Error in GetX509Certificate2(String thumbprint)  Error: {0}", ex.Message));

                x509Certificate2 = null;
            }
            finally
            {
                store.Close();
            }

            return x509Certificate2;
        }
示例#24
0
		private void ConfigureCertificates()
		{
			_certificate = _appleSettings.Certificate;

			_certificates = new X509CertificateCollection();

			if (_appleSettings.AddLocalAndMachineCertificateStores)
			{
				var store = new X509Store(StoreLocation.LocalMachine);
				_certificates.AddRange(store.Certificates);

				store = new X509Store(StoreLocation.CurrentUser);
				_certificates.AddRange(store.Certificates);
			}

			_certificates.Add(_certificate);

			if (_appleSettings.AdditionalCertificates != null)
			{
				foreach (var additionalCertificate in _appleSettings.AdditionalCertificates)
				{
					_certificates.Add(additionalCertificate);
				}
			}
		}
示例#25
0
文件: TestHost.cs 项目: yxbdali/wcf
        public static X509Certificate2 CertificateFromFriendlyName(StoreName name, StoreLocation location, string friendlyName)
        {
            X509Store store = null;

            try
            {
                store = new X509Store(name, location);
                store.Open(OpenFlags.ReadOnly);

                X509Certificate2Collection foundCertificates = store.Certificates.Find(X509FindType.FindByIssuerName, "DO_NOT_TRUST_WcfBridgeRootCA", false);
                foreach (X509Certificate2 cert in foundCertificates)
                {
                    if (cert.FriendlyName == friendlyName)
                    {
                        return cert;
                    }
                }
                return null;
            }
            finally
            {
                if (store != null)
                {
                    store.Close();
                }
            }
        }
示例#26
0
        private static System.Security.Cryptography.X509Certificates.X509Certificate2 LoadCertificate(EndpointConfiguration config, IWebHostEnvironment environment)
        {
            if (config.StoreName != null && config.StoreLocation != null)
            {
                using (var store = new System.Security.Cryptography.X509Certificates.X509Store(config.StoreName, Enum.Parse <StoreLocation>(config.StoreLocation)))
                {
                    store.Open(OpenFlags.ReadOnly);
                    var certificate = store.Certificates.Find(
                        X509FindType.FindBySubjectName,
                        config.Host,
                        validOnly: !environment.IsDevelopment());

                    if (certificate.Count == 0)
                    {
                        throw new InvalidOperationException($"Certificate not found for {config.Host}.");
                    }

                    return(certificate[0]);
                }
            }

            if (config.FilePath != null && config.Password != null)
            {
                return(new X509Certificate2(config.FilePath, config.Password));
            }

            throw new InvalidOperationException("No valid certificate configuration found for the current endpoint.");
        }
        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);
        }
        private static X509Certificate GetAppleServerCert(string thumbprint)
        {
            X509Store store;
            store = new X509Store(StoreLocation.CurrentUser);

            if (store != null)
            {
                store.Open(OpenFlags.ReadOnly);

                X509Certificate2Collection certs = store.Certificates;

                if (certs.Count > 0)
                {
                    for (int i = 0; i < certs.Count; i++)
                    {
                        X509Certificate2 cert = certs[i];

                        if (cert.Thumbprint.Equals(thumbprint, StringComparison.InvariantCultureIgnoreCase))
                        {
                            return certs[i];
                        }
                    }
                }
            }

            Trace.TraceError("Could not find the certification containing: {0} ", "R5QS56362W:R5QS56362W");

            throw new InvalidDataException("Could not find the Apple Push Notification certificate");
        }
示例#29
0
        private void btnGenerateCert_Click(object sender, EventArgs e)
        {
            byte[] pfxData = Certificate.CreateSelfSignCertificatePfx("CN=" + txtCertName.Text,
                DateTime.Now, DateTime.Now.AddYears(30), "abcTest");
            //MessageBox.Show(StringUtils.ByteArrayToHexString(pfxData));

            X509Store store = null;
            try
            {
                if (chkSaveInCurrentUser.Checked)
                    store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                else
                    store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

                store.Open(OpenFlags.ReadWrite);

                X509Certificate2 pc = new X509Certificate2(pfxData, "abcTest", X509KeyStorageFlags.Exportable);
                store.Add(pc);

                store.Close();

                ShowExportData(pc);
            }
            finally
            {
                if (store != null)
                    store.Close();
            }
        }
        public X509Certificate2 GetCertificate(string thumbprint, StoreLocation storeLocation)
        {
            X509Store certStore = new X509Store(StoreName.My, storeLocation);
            X509Certificate2 certToUse = null;
            try
            {
                try
                {
                    certStore.Open(OpenFlags.ReadOnly);
                }
                catch (Exception ex)
                {
                    var outerEx = new Exception("Failed to open X509Store My on CurrentUser.", ex);
                    throw outerEx;
                }
                var primaryCertificateThumbprint = thumbprint.ToLower();

                var certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, primaryCertificateThumbprint, false);
                if (certCollection == null || certCollection.Count == 0)
                {
                    return null;
                }
                certToUse = certCollection[0];
                if (certToUse.Thumbprint.ToLower() != primaryCertificateThumbprint.ToLower())
                {
                    return null;
                }
            }
            finally
            {
                certStore.Close();
            }
            return certToUse;
        }
示例#31
0
        public ApplePushChannel(ApplePushChannelSettings channelSettings, PushServiceSettings serviceSettings = null)
            : base(channelSettings, serviceSettings)
        {
            this.appleSettings = channelSettings;

            certificate = this.appleSettings.Certificate;

            certificates = new X509CertificateCollection();

            if (appleSettings.AddLocalAndMachineCertificateStores)
            {
                var store = new X509Store(StoreLocation.LocalMachine);
                certificates.AddRange(store.Certificates);

                store = new X509Store(StoreLocation.CurrentUser);
                certificates.AddRange(store.Certificates);
            }

            certificates.Add(certificate);

            if (this.appleSettings.AdditionalCertificates != null)
                foreach (var addlCert in this.appleSettings.AdditionalCertificates)
                    certificates.Add(addlCert);

            //Start our cleanup task
            taskCleanup = new Task(() => Cleanup(), TaskCreationOptions.LongRunning);
            taskCleanup.ContinueWith((t) => { var ex = t.Exception; }, TaskContinuationOptions.OnlyOnFaulted);
            taskCleanup.Start();
        }
        /// <summary>
        /// Gets a reference to Certificate store handle in the supplied <see cref="X509Store"/> object.
        /// </summary>
        /// <param name="store">The store.</param>
        /// <returns></returns>
        public static CertStoreHandle FromX509Store(X509Store store)
        {
            if (store == null) return InvalidHandle;

            // the handle is owned by the X509Store object. We shouldn't release it!
            return new CertStoreHandle(store.StoreHandle, false); 
        }
示例#33
0
 public CertificateStore(string machine)
 {
     var storename = String.IsNullOrEmpty(machine) || String.Compare("localhost", machine, StringComparison.OrdinalIgnoreCase) == 0
         ? "MY"
         : @"\\{0}\MY".FormatWith(machine);
     _store = new X509Store(storename.FormatWith(machine), StoreLocation.LocalMachine);
 }
示例#34
0
        public X509Certificate2 GetBySerialNumber(string serialNumber, StoreLocation storeLocation, StoreName storeName)
        {
            X509Store store = new X509Store(storeName, storeLocation);
              var matchingCertificates = this.findAllCertificatesInStore(store, (s) => { return s.Certificates.Find(X509FindType.FindBySerialNumber, serialNumber, true); });

              return this.getSingleCertificate(matchingCertificates);
        }
示例#35
0
 /// <summary>
 /// Gets a X509 certificate from windows store. Asks the user for the correct certificate.
 /// </summary>
 /// <returns></returns>
 public static X509Certificate2 GetCertificate()
 {
     var st = new X509Store(StoreName.My, StoreLocation.CurrentUser);
     st.Open(OpenFlags.ReadOnly);
     X509Certificate2 card = null;
     try
     {
         X509Certificate2Collection col = st.Certificates;
         X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, "Certificates",
                                          "Select one to sign",
                                          X509SelectionFlag.
                                          SingleSelection);
         if (sel.Count > 0)
         {
             X509Certificate2Enumerator en = sel.GetEnumerator();
             en.MoveNext();
             card = en.Current;
         }
     }
     finally
     {
         st.Close();
     }
     return card;
 }
示例#36
0
        public async Task StartServerAsync()
        {
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);

            //var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, "f864d23e92894c56df566b7ab7a9c6411d50d14d", false);
            var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, "3fd0b5f28dc32f5f0bb9f44cf1f6816846e44cbe", false);
            
            if (certificates.Count == 0)
            {
                throw new InvalidOperationException("Server certificate not found");
            }

            store.Close();
#if DEBUG
            ITraceWriter traceWriter = new DebugTraceWriter("Server"); 
#else
            ITraceWriter traceWriter = new FileTraceWriter("server.log"); 
#endif

            _listener = new TcpTransportListener(
                _listenerUri,
                certificates[0],
                new EnvelopeSerializer(),
                traceWriter
                );


            await _listener.StartAsync();
        }
示例#37
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;
        }
示例#38
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();
        }
        /// <summary>
        /// Loads the specified system keystore and puts
        /// the keys store in read-only mode
        /// </summary>
        /// <param name="storeName">one of the enum values </param>
        /// <param name="storelocation">one of the enum values</param>
        public void Load(SystemX509.StoreName storeName, SystemX509.StoreLocation storelocation)
        {
            ReadOnlyKeyStore = true;
            _listItems.Clear();
            var store = new SystemX509.X509Store(storeName, storelocation);

            store.Open(SystemX509.OpenFlags.ReadOnly);
            foreach (SystemX509.X509Certificate2 cert in store.Certificates)
            {
                AddEntry(cert.FriendlyName, DotNetUtilities.FromX509Certificate(cert), null);
            }
        }
示例#40
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;
        }
示例#41
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));
        }
示例#42
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();
     }
 }
        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();
            }
        }
示例#44
0
        private static System.Security.Cryptography.X509Certificates.X509Certificate2 FindCert(string pkiinfo)
        {
            System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine);
            store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
            X509Certificate2Collection col = store.Certificates.Find(System.Security.Cryptography.X509Certificates.X509FindType.FindBySerialNumber, pkiinfo, true);

            store.Close();
            if (col != null && col.Count > 0)
            {
                //if (col.Count > 1)

                return(col[0]);
            }
            throw new ConfigurationErrorsException("no certificates were found matching that serial number");
        }
示例#45
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);
        }
示例#46
0
        public static bool SetupSsl(int port)
        {
            System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine);
            //Use the first cert to configure Ssl
            store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
            //Assumption is we have certs. If not then this call will fail :(
            try
            {
                bool found = false;
                foreach (System.Security.Cryptography.X509Certificates.X509Certificate2 cert in store.Certificates)
                {
                    String certHash = cert.GetCertHashString();
                    //Only install certs issued for the machine and has the name as the machine name
                    if (cert.Subject.ToUpper().IndexOf(Environment.MachineName.ToUpper()) >= 0)
                    {
                        try
                        {
                            found = true;
                            //ExecuteNetsh(String.Format("set ssl -i 0.0.0.0:{1} -c \"MY\" -h {0}", certHash, port));
                            ExecuteNetsh(string.Format("http add sslcert ipport=0.0.0.0:{0} certhash={1} appid={{{2}}}", port, certHash, Guid.NewGuid().ToString()));
                        }
                        catch (Exception e)
                        {
                            return(false);
                        }
                    }
                }

                if (!found)
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                return(false);
            }
            finally
            {
                if (store != null)
                {
                    store.Close();
                }
            }

            return(true);
        }
示例#47
0
        static public bool checkCertificateInstalled()
        {
            System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByIssuerName, ConfirmedConstants.endPoint("www"), true);

            if (certs.Count > 0)
            {
                for (int i = 0; i < certs.Count; i++)
                {
                    if (certs[i].IssuerName.Name.ToString() == "CN=" + ConfirmedConstants.endPoint("www"))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
示例#48
0
        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;
        }
示例#49
0
        public static RsaCipher LoadFromX509Store(string friendlyName)
        {
            System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(StoreName.My);
            try
            {
                store.Open(OpenFlags.ReadOnly);
                foreach (var x509 in store.Certificates)
                {
                    var cn = x509.FriendlyName;
                    if (cn == friendlyName)
                    {
                        var key = new RsaCipherKey();
                        try
                        {
                            #if NETSTANDARD2_0
                            key.Public  = x509.GetRSAPublicKey();
                            key.Private = x509.GetRSAPrivateKey();
                            #endif

                            #if NETFX
                            key.Public  = (RSACryptoServiceProvider)x509.PublicKey.Key;
                            key.Private = (RSACryptoServiceProvider)x509.PrivateKey;
                            #endif
                        }
                        catch (Exception)
                        {
                            key.Dispose();
                            throw;
                        }

                        RsaCipher rsaCipher = new RsaCipher();
                        rsaCipher._key = key;
                        return(rsaCipher);
                    }
                }
            }
            finally
            {
                #if NETSTANDARD2_0
                store.Dispose();
                #endif
            }
            throw new InternalErrorException("Certificate not found: " + friendlyName);
        }
示例#50
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);
        }
示例#51
0
        public static X509Certificate2 FindCertificate(string certificateThumbprint)
        {
            X509Certificate2 foundCert = null;
            var store = new System.Security.Cryptography.X509Certificates.X509Store(StoreName.My, StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadOnly);

            foreach (var cert in store.Certificates)
            {
                if (cert.Thumbprint.Equals(certificateThumbprint))
                {
                    foundCert = cert;
                    break;
                }
            }

            store.Close();

            return(foundCert);
        }
示例#52
0
        public static void RemoveCertificateFromLocalStoreByThumbprint(string thumbPrint)
        {
            using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
            {
                store.Open(OpenFlags.ReadWrite | OpenFlags.IncludeArchived);

                // You could also use a more specific find type such as X509FindType.FindByThumbprint
                X509Certificate2Collection col =
                    store.Certificates.Find(X509FindType.FindByThumbprint, thumbPrint, false);

                foreach (var cert in col)
                {
                    // Remove the certificate
                    store.Remove(cert);
                    TryRemovePrivateKey(cert);
                }

                store.Close();
            }
        }
示例#53
0
        /// <summary>
        /// Find certificate in store
        /// </summary>
        /// <param name="thumbPrint"></param>
        /// <param name="storeName"></param>
        /// <param name="storeLocation"></param>
        /// <returns></returns>
        public static X509Certificate2 FindCertificate(string thumbPrint, StoreName storeName, StoreLocation storeLocation)
        {
            X509Certificate2 certificate = null;

            X509Store store = new X509Store(storeName, storeLocation);

            store.Open(OpenFlags.ReadOnly | OpenFlags.IncludeArchived);

            // You could also use a more specific find type such as X509FindType.FindByThumbprint
            X509Certificate2Collection col =
                store.Certificates.Find(X509FindType.FindByThumbprint, thumbPrint, false);

            foreach (var cert in col)
            {
                certificate = cert;
            }

            store.Close();

            return(certificate);
        }
示例#54
0
        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");
            }
        }
 private static System.Security.Cryptography.X509Certificates.X509Certificate2 selectcert() //select cert from store & set selectedcert
 {
     try
     {
         System.Security.Cryptography.X509Certificates.X509Store mystore = new System.Security.Cryptography.X509Certificates.X509Store(StoreLocation.CurrentUser);
         mystore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
         X509Certificate2Collection certCollection     = (X509Certificate2Collection)mystore.Certificates;
         X509Certificate2Collection foundCollection    = (X509Certificate2Collection)certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
         X509Certificate2Collection selectedcollection = X509Certificate2UI.SelectFromCollection(foundCollection, "Select a Certificate.", "Select a Certificate from the following list to get information on that certificate", X509SelectionFlag.SingleSelection);
         if (selectedcollection.Count > 0)
         {
             X509Certificate2 certz = selectedcollection[0];
             return(certz);
         }
         return(null);
     }
     catch (Exception e)
     {
         MessageBox.Show(e.Message);
         return(null);
     }
 }
示例#56
0
 public bool CheckCertificate()
 {
     try
     {
         System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(StoreName.My, StoreLocation.LocalMachine);
         store.Open(OpenFlags.ReadOnly); // Dont forget. otherwise u will get an exception.
         X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, "2020ImagingLtd", true);
         if (certs.Count > 0)
         {
             // Certificate is found.
             return(true);
         }
         else
         {
             return(false);
             // No Certificate found by that subject name.
         }
     }
     catch (Exception ex)
     { }
     return(false);
 }
示例#57
0
 public bool RemoveCertFromLMStore(X509Certificate2 x509cert)
 {
     System.Security.Cryptography.X509Certificates.X509Store store = null;
     try
     {
         store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
         store.Open(OpenFlags.ReadWrite);
         store.Remove(x509cert);
         return(true);
     }
     catch (Exception ex)
     {
         ServerComms.LogError($@"Unable to remove cert from CA Store, error {ex.Message}");
         return(false);
     }
     finally
     {
         if (null != store)
         {
             store.Close();
         }
     }
 }
        public static X509Certificates.X509Certificate2 LoadCertificate(string hostname)
        {
            var x509Store = new X509Certificates.X509Store(X509Certificates.StoreName.Root, X509Certificates.StoreLocation.CurrentUser);

            x509Store.Open(X509Certificates.OpenFlags.ReadOnly);
            var inStr = $"CN={hostname}";

            try
            {
                foreach (var certificate in x509Store.Certificates)
                {
                    if (certificate.Subject.StartsWith(inStr))
                    {
                        return(certificate);
                    }
                }
            }
            finally
            {
                x509Store.Close();
            }
            return(null);
        }
示例#59
0
        /*private void WriteCertificate(string name, byte[] raw)
         * {
         *  using(FileStream stream = new FileStream(GetCertificateFilePath(name), FileMode.Create, FileAccess.Write))
         *      stream.Write(raw, 0, raw.Length);
         * }*/

        private MSX509.X509Certificate2 LoadCertificate(string name, MSX509.StoreName storeName, MSX509.StoreLocation location)
        {
            if (certificates_.ContainsKey(name))
            {
                return(certificates_[name]);
            }

            MSX509.X509Store store = new MSX509.X509Store(storeName, location);
            store.Open(MSX509.OpenFlags.ReadOnly);
            var certificates = store.Certificates.Find(MSX509.X509FindType.FindBySubjectName, name, true);

            store.Close();

            if (certificates.Count <= 0)
            {
                return(null);
            }

            state_.Logger.Information("X509v3 '{0}' loaded from store", name);

            MSX509.X509Certificate2 certificate = certificates[0];
            certificates_[name] = certificate;
            return(certificate);
        }
        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); }
        }