AddRange() public method

public AddRange ( System certificates ) : void
certificates System
return void
コード例 #1
0
 private static System.Security.Cryptography.SafeCertStoreHandle BuildDecryptorStore(X509Certificate2Collection extraStore)
 {
     X509Certificate2Collection collection = new X509Certificate2Collection();
     try
     {
         X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
         store.Open(OpenFlags.IncludeArchived | OpenFlags.OpenExistingOnly);
         collection.AddRange(store.Certificates);
     }
     catch (SecurityException)
     {
     }
     try
     {
         X509Store store2 = new X509Store("MY", StoreLocation.LocalMachine);
         store2.Open(OpenFlags.IncludeArchived | OpenFlags.OpenExistingOnly);
         collection.AddRange(store2.Certificates);
     }
     catch (SecurityException)
     {
     }
     if (extraStore != null)
     {
         collection.AddRange(extraStore);
     }
     if (collection.Count == 0)
     {
         throw new CryptographicException(-2146889717);
     }
     return System.Security.Cryptography.X509Certificates.X509Utils.ExportToMemoryStore(collection);
 }
コード例 #2
0
 internal static X509Certificate2Collection CreateBagOfCertificates(CmsSigner signer)
 {
     X509Certificate2Collection certificates = new X509Certificate2Collection();
     certificates.AddRange(signer.Certificates);
     if (signer.IncludeOption != X509IncludeOption.None)
     {
         if (signer.IncludeOption == X509IncludeOption.EndCertOnly)
         {
             certificates.Add(signer.Certificate);
             return certificates;
         }
         int count = 1;
         X509Chain chain = new X509Chain();
         chain.Build(signer.Certificate);
         if ((chain.ChainStatus.Length > 0) && ((chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain))
         {
             throw new CryptographicException(-2146762486);
         }
         if (signer.IncludeOption == X509IncludeOption.WholeChain)
         {
             count = chain.ChainElements.Count;
         }
         else if (chain.ChainElements.Count > 1)
         {
             count = chain.ChainElements.Count - 1;
         }
         for (int i = 0; i < count; i++)
         {
             certificates.Add(chain.ChainElements[i].Certificate);
         }
     }
     return certificates;
 }
コード例 #3
0
ファイル: CertTool.cs プロジェクト: lsgxeva/MIEngine
        private static void Main(string[] args)
        {
            Task.Run(async () =>
            {
                Console.WriteLine("Enter PIN: ");
                string pin = Console.ReadLine();

                WebRequestHandler handler = new WebRequestHandler();
                handler.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);

                using (HttpClient client = new HttpClient(handler, true))
                {
                    client.BaseAddress = new Uri(string.Format(@"https://{0}:{1}", MachineName, RemotePort));

                    X509Store store = null;

                    try
                    {
                        var response = await client.GetAsync("certs/" + pin);
                        response.EnsureSuccessStatusCode();

                        byte[] rawCert = await response.Content.ReadAsByteArrayAsync();

                        X509Certificate2Collection certs = new X509Certificate2Collection();
                        certs.Import(rawCert, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.UserKeySet);

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

                        X509Certificate2Collection oldCerts = new X509Certificate2Collection();

                        foreach (var cert in certs)
                        {
                            oldCerts.AddRange(store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.Subject, false));
                        }
                        store.RemoveRange(certs);
                        store.AddRange(certs);
                        store.Close();

                        Console.WriteLine("Success");
                    }
                    catch (HttpRequestException e)
                    {
                        Console.WriteLine("Error communicating with vcremote. Make sure that vcremote is running in secure mode and that a new client cert has been generated.");
                    }
                    finally
                    {
                        if (store != null)
                        {
                            store.Close();
                        }
                    }
                }
            }).Wait();
        }
コード例 #4
0
        public override void Configure(IOfferRemoteComposition server)
        {
            if (_copyCertFromFile)
            {
                var cert = new X509Certificate2(_certFile);
                ConfigureCertInstall(server, cert);
            }
            else
            {
                var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

                try
                {
                    var certs = new X509Certificate2Collection();

                    if (_certFriendlyName != null)
                    {
                        certs.AddRange(store.Certificates.Cast<X509Certificate2>().Where(cert => cert.FriendlyName == _certFriendlyName).ToArray());
                    }
                    else
                    {
                        certs.AddRange(store.Certificates.Find(_findType, _searchString, true));
                    }

                    if (certs.Count != 1)
                    {
                        if (certs.Count < 1)
                            throw new ConDepCertificateNotFoundException("Certificate not found");

                        throw new ConDepCertificateDuplicationException("More than one certificate found in search");
                    }

                    ConfigureCertInstall(server, certs[0]);
                }
                finally
                {
                    store.Close();
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="findBy"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static X509Certificate2 FindCertificateAcrossCertStore(X509FindType findBy, string value)
        {
            var certColl = new X509Certificate2Collection();
            foreach (var e in (StoreName[])Enum.GetValues(typeof(StoreName)))
            {
                var store = new X509Store(e, StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly);

                certColl.AddRange(store.Certificates.Find(findBy, value, false));

                store.Close();

                if (certColl.Count != 0)
                {
                    return certColl[0];
                }
            }

            throw new Exception("Certificate not found: " + value);
        }
コード例 #6
0
ファイル: Instance.cs プロジェクト: sbesson/zeroc-ice
        internal void initialize()
        {
            if(_initialized)
            {
                return;
            }

            const string prefix = "IceSSL.";
            Ice.Properties properties = communicator().getProperties();

            //
            // Check for a default directory. We look in this directory for
            // files mentioned in the configuration.
            //
            _defaultDir = properties.getProperty(prefix + "DefaultDir");


            string keySet = properties.getPropertyWithDefault(prefix + "KeySet", "DefaultKeySet");
            if(!keySet.Equals("DefaultKeySet") && !keySet.Equals("UserKeySet") && !keySet.Equals("MachineKeySet"))
            {
                keySet = "DefaultKeySet";
                _logger.warning("Invalid IceSSL.KeySet value `" + keySet + "' adjusted to `DefaultKeySet'");
            }

            X509KeyStorageFlags keyStorageFlags = X509KeyStorageFlags.DefaultKeySet;
            if(keySet.Equals("UserKeySet"))
            {
                keyStorageFlags = X509KeyStorageFlags.UserKeySet;
            }
            else if(keySet.Equals("MachineKeySet"))
            {
                keyStorageFlags = X509KeyStorageFlags.MachineKeySet;
            }

            if(properties.getPropertyAsIntWithDefault(prefix + "PersistKeySet", 0) > 0)
            {
                keyStorageFlags |= X509KeyStorageFlags.PersistKeySet;
            }

            //
            // Process IceSSL.ImportCert.* properties.
            //
            Dictionary<string, string> certs = properties.getPropertiesForPrefix(prefix + "ImportCert.");
            foreach(KeyValuePair<string, string> entry in certs)
            {
                string name = entry.Key;
                string val = entry.Value;
                if(val.Length > 0)
                {
                    importCertificate(name, val, keyStorageFlags);
                }
            }

            //
            // Select protocols.
            //
            _protocols = parseProtocols(prefix + "Protocols");

            //
            // CheckCertName determines whether we compare the name in a peer's
            // certificate against its hostname.
            //
            _checkCertName = properties.getPropertyAsIntWithDefault(prefix + "CheckCertName", 0) > 0;

            //
            // VerifyDepthMax establishes the maximum length of a peer's certificate
            // chain, including the peer's certificate. A value of 0 means there is
            // no maximum.
            //
            _verifyDepthMax = properties.getPropertyAsIntWithDefault(prefix + "VerifyDepthMax", 2);

            //
            // CheckCRL determines whether the certificate revocation list is checked, and how strictly.
            //
            _checkCRL = properties.getPropertyAsIntWithDefault(prefix + "CheckCRL", 0);

            //
            // Check for a certificate verifier.
            //
            string certVerifierClass = properties.getProperty(prefix + "CertVerifier");
            if(certVerifierClass.Length > 0)
            {
                if(_verifier != null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: certificate verifier already installed";
                    throw e;
                }

                Type cls = _facade.findType(certVerifierClass);
                if(cls == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load certificate verifier class " + certVerifierClass;
                    throw e;
                }

                try
                {
                    _verifier = (CertificateVerifier)IceInternal.AssemblyUtil.createInstance(cls);
                }
                catch(Exception ex)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                    e.reason = "IceSSL: unable to instantiate certificate verifier class " + certVerifierClass;
                    throw e;
                }

                if(_verifier == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to instantiate certificate verifier class " + certVerifierClass;
                    throw e;
                }
            }

            //
            // Check for a password callback.
            //
            string passwordCallbackClass = properties.getProperty(prefix + "PasswordCallback");
            if(passwordCallbackClass.Length > 0)
            {
                if(_passwordCallback != null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: password callback already installed";
                    throw e;
                }

                Type cls = _facade.findType(passwordCallbackClass);
                if(cls == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }

                try
                {
                    _passwordCallback = (PasswordCallback)IceInternal.AssemblyUtil.createInstance(cls);
                }
                catch(Exception ex)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }

                if(_passwordCallback == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }
            }

            //
            // If the user hasn't supplied a certificate collection, we need to examine
            // the property settings.
            //
            if(_certs == null)
            {
                //
                // If IceSSL.CertFile is defined, load a certificate from a file and
                // add it to the collection.
                //
                // TODO: tracing?
                _certs = new X509Certificate2Collection();
                string certFile = properties.getProperty(prefix + "CertFile");
                string passwordStr = properties.getProperty(prefix + "Password");
                
                if(certFile.Length > 0)
                {
                    if(!checkPath(ref certFile))
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                        e.reason = "IceSSL: certificate file not found: " + certFile;
                        throw e;
                    }

                    SecureString password = null;
                    if(passwordStr.Length > 0)
                    {
                        password = createSecureString(passwordStr);
                    }
                    else if(_passwordCallback != null)
                    {
                        password = _passwordCallback.getPassword(certFile);
                    }

                    try
                    {
                        X509Certificate2 cert;
                        if(password != null)
                        {
                            cert = new X509Certificate2(certFile, password, keyStorageFlags);
                        }
                        else
                        {
                            cert = new X509Certificate2(certFile, "", keyStorageFlags);
                        }
                        _certs.Add(cert);
                    }
                    catch(CryptographicException ex)
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                        e.reason = "IceSSL: error while attempting to load certificate from " + certFile;
                        throw e;
                    }
                }

                //
                // If IceSSL.FindCert.* properties are defined, add the selected certificates
                // to the collection.
                //
                // TODO: tracing?
                const string findPrefix = prefix + "FindCert.";
                Dictionary<string, string> certProps = properties.getPropertiesForPrefix(findPrefix);
                if(certProps.Count > 0)
                {
                    foreach(KeyValuePair<string, string> entry in certProps)
                    {
                        string name = entry.Key;
                        string val = entry.Value;
                        if(val.Length > 0)
                        {
                            string storeSpec = name.Substring(findPrefix.Length);
                            X509Certificate2Collection coll = findCertificates(name, storeSpec, val);
                            _certs.AddRange(coll);
                        }
                    }
                    if(_certs.Count == 0)
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                        e.reason = "IceSSL: no certificates found";
                        throw e;
                    }
                }
            }

            _initialized = true;
        }
コード例 #7
0
        internal static X509Certificate2Collection BuildBagOfCerts(KeyInfoX509Data keyInfoX509Data, CertUsageType certUsageType)
        {
            X509Certificate2Collection certificates = new X509Certificate2Collection();
            ArrayList list = (certUsageType == CertUsageType.Decryption) ? new ArrayList() : null;
            if (keyInfoX509Data.Certificates != null)
            {
                foreach (X509Certificate2 certificate in keyInfoX509Data.Certificates)
                {
                    switch (certUsageType)
                    {
                        case CertUsageType.Verification:
                            certificates.Add(certificate);
                            break;

                        case CertUsageType.Decryption:
                            list.Add(new X509IssuerSerial(certificate.IssuerName.Name, certificate.SerialNumber));
                            break;
                    }
                }
            }
            if (((keyInfoX509Data.SubjectNames != null) || (keyInfoX509Data.IssuerSerials != null)) || ((keyInfoX509Data.SubjectKeyIds != null) || (list != null)))
            {
                new StorePermission(StorePermissionFlags.OpenStore).Assert();
                X509Store[] storeArray = new X509Store[2];
                string storeName = (certUsageType == CertUsageType.Verification) ? "AddressBook" : "My";
                storeArray[0] = new X509Store(storeName, StoreLocation.CurrentUser);
                storeArray[1] = new X509Store(storeName, StoreLocation.LocalMachine);
                for (int i = 0; i < storeArray.Length; i++)
                {
                    if (storeArray[i] != null)
                    {
                        X509Certificate2Collection certificates2 = null;
                        try
                        {
                            storeArray[i].Open(OpenFlags.OpenExistingOnly);
                            certificates2 = storeArray[i].Certificates;
                            storeArray[i].Close();
                            if (keyInfoX509Data.SubjectNames != null)
                            {
                                foreach (string str2 in keyInfoX509Data.SubjectNames)
                                {
                                    certificates2 = certificates2.Find(X509FindType.FindBySubjectDistinguishedName, str2, false);
                                }
                            }
                            if (keyInfoX509Data.IssuerSerials != null)
                            {
                                foreach (X509IssuerSerial serial in keyInfoX509Data.IssuerSerials)
                                {
                                    certificates2 = certificates2.Find(X509FindType.FindByIssuerDistinguishedName, serial.IssuerName, false);
                                    certificates2 = certificates2.Find(X509FindType.FindBySerialNumber, serial.SerialNumber, false);
                                }
                            }
                            if (keyInfoX509Data.SubjectKeyIds != null)
                            {
                                foreach (byte[] buffer in keyInfoX509Data.SubjectKeyIds)
                                {
                                    string findValue = System.Security.Cryptography.X509Certificates.X509Utils.EncodeHexString(buffer);
                                    certificates2 = certificates2.Find(X509FindType.FindBySubjectKeyIdentifier, findValue, false);
                                }
                            }
                            if (list != null)
                            {
                                foreach (X509IssuerSerial serial2 in list)
                                {
                                    certificates2 = certificates2.Find(X509FindType.FindByIssuerDistinguishedName, serial2.IssuerName, false);
                                    certificates2 = certificates2.Find(X509FindType.FindBySerialNumber, serial2.SerialNumber, false);
                                }
                            }
                        }
                        catch (CryptographicException)
                        {
                        }
                        if (certificates2 != null)
                        {
                            certificates.AddRange(certificates2);
                        }
                    }
                }
            }
            return certificates;
        }
コード例 #8
0
ファイル: SSLEngine.cs プロジェクト: joshmoore/ice
        internal void initialize()
        {
            if(_initialized)
            {
                return;
            }

            const string prefix = "IceSSL.";
            Ice.Properties properties = communicator().getProperties();

            //
            // Check for a default directory. We look in this directory for
            // files mentioned in the configuration.
            //
            _defaultDir = properties.getProperty(prefix + "DefaultDir");

            string certStoreLocation = properties.getPropertyWithDefault(prefix + "CertStoreLocation", "CurrentUser");
            StoreLocation storeLocation;
            if(certStoreLocation == "CurrentUser")
            {
                storeLocation = StoreLocation.CurrentUser;
            }
            else if(certStoreLocation == "LocalMachine")
            {
                storeLocation = StoreLocation.LocalMachine;
            }
            else
            {
                _logger.warning("Invalid IceSSL.CertStoreLocation value `" + certStoreLocation +
                                "' adjusted to `CurrentUser'");
                storeLocation = StoreLocation.CurrentUser;
            }
            _useMachineContext = certStoreLocation == "LocalMachine";

#if !UNITY
            X509KeyStorageFlags keyStorageFlags;
            if(_useMachineContext)
            {
                keyStorageFlags = X509KeyStorageFlags.MachineKeySet;
            }
            else
            {
                keyStorageFlags = X509KeyStorageFlags.UserKeySet;
            }

            string keySet = properties.getProperty(prefix + "KeySet"); // Deprecated property
            if(keySet.Length > 0)
            {
                if(keySet.Equals("DefaultKeySet"))
                {
                    keyStorageFlags = X509KeyStorageFlags.DefaultKeySet;
                }
                else if(keySet.Equals("UserKeySet"))
                {
                    keyStorageFlags = X509KeyStorageFlags.UserKeySet;
                }
                else if(keySet.Equals("MachineKeySet"))
                {
                    keyStorageFlags = X509KeyStorageFlags.MachineKeySet;
                }
                else
                {
                    _logger.warning("Invalid IceSSL.KeySet value `" + keySet + "' adjusted to `DefaultKeySet'");
                    keyStorageFlags = X509KeyStorageFlags.DefaultKeySet;
                }
            }

            if(properties.getPropertyAsIntWithDefault(prefix + "PersistKeySet", 0) > 0) // Deprecated property
            {
                keyStorageFlags |= X509KeyStorageFlags.PersistKeySet;
            }

            //
            // Process IceSSL.ImportCert.* properties.
            //
            Dictionary<string, string> certs = properties.getPropertiesForPrefix(prefix + "ImportCert.");
            foreach(KeyValuePair<string, string> entry in certs)
            {
                string name = entry.Key;
                string val = entry.Value;
                if(val.Length > 0)
                {
                    importCertificate(name, val, keyStorageFlags);
                }
            }
#endif

            //
            // Protocols selects which protocols to enable, by default we only enable TLS1.0
            // TLS1.1 and TLS1.2 to avoid security issues with SSLv3
            //
            _protocols = parseProtocols(
                properties.getPropertyAsListWithDefault(prefix + "Protocols",
#if UNITY
                                                        new string[]{"TLS1_0"}));
#else
                                                        _tls12Support ? new string[]{"TLS1_0", "TLS1_1", "TLS1_2"} :
                                                                        new string[]{"TLS1_0", "TLS1_1"}));
#endif
            //
            // CheckCertName determines whether we compare the name in a peer's
            // certificate against its hostname.
            //
            _checkCertName = properties.getPropertyAsIntWithDefault(prefix + "CheckCertName", 0) > 0;

            //
            // VerifyDepthMax establishes the maximum length of a peer's certificate
            // chain, including the peer's certificate. A value of 0 means there is
            // no maximum.
            //
            _verifyDepthMax = properties.getPropertyAsIntWithDefault(prefix + "VerifyDepthMax", 3);

            //
            // CheckCRL determines whether the certificate revocation list is checked, and how strictly.
            //
            _checkCRL = properties.getPropertyAsIntWithDefault(prefix + "CheckCRL", 0);

#if !UNITY
            //
            // Check for a certificate verifier.
            //
            string certVerifierClass = properties.getProperty(prefix + "CertVerifier");
            if(certVerifierClass.Length > 0)
            {
                if(_verifier != null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: certificate verifier already installed";
                    throw e;
                }

                Type cls = _facade.findType(certVerifierClass);
                if(cls == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load certificate verifier class " + certVerifierClass;
                    throw e;
                }

                try
                {
                    _verifier = (CertificateVerifier)IceInternal.AssemblyUtil.createInstance(cls);
                }
                catch(Exception ex)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                    e.reason = "IceSSL: unable to instantiate certificate verifier class " + certVerifierClass;
                    throw e;
                }

                if(_verifier == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to instantiate certificate verifier class " + certVerifierClass;
                    throw e;
                }
            }

            //
            // Check for a password callback.
            //
            string passwordCallbackClass = properties.getProperty(prefix + "PasswordCallback");
            if(passwordCallbackClass.Length > 0)
            {
                if(_passwordCallback != null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: password callback already installed";
                    throw e;
                }

                Type cls = _facade.findType(passwordCallbackClass);
                if(cls == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }

                try
                {
                    _passwordCallback = (PasswordCallback)IceInternal.AssemblyUtil.createInstance(cls);
                }
                catch(Exception ex)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }

                if(_passwordCallback == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }
            }

            //
            // If the user hasn't supplied a certificate collection, we need to examine
            // the property settings.
            //
            if(_certs == null)
            {
                //
                // If IceSSL.CertFile is defined, load a certificate from a file and
                // add it to the collection.
                //
                // TODO: tracing?
                _certs = new X509Certificate2Collection();
                string certFile = properties.getProperty(prefix + "CertFile");
                string passwordStr = properties.getProperty(prefix + "Password");
                string findCert = properties.getProperty(prefix + "FindCert");
                const string findPrefix = prefix + "FindCert.";
                Dictionary<string, string> findCertProps = properties.getPropertiesForPrefix(findPrefix);

                if(certFile.Length > 0)
                {
                    if(!checkPath(ref certFile))
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                        e.reason = "IceSSL: certificate file not found: " + certFile;
                        throw e;
                    }

                    SecureString password = null;
                    if(passwordStr.Length > 0)
                    {
                        password = createSecureString(passwordStr);
                    }
                    else if(_passwordCallback != null)
                    {
                        password = _passwordCallback.getPassword(certFile);
                    }

                    try
                    {
                        X509Certificate2 cert;
                        X509KeyStorageFlags importFlags;
                        if(_useMachineContext)
                        {
                            importFlags = X509KeyStorageFlags.MachineKeySet;
                        }
                        else
                        {
                            importFlags = X509KeyStorageFlags.UserKeySet;
                        }

                        if(password != null)
                        {
                            cert = new X509Certificate2(certFile, password, importFlags);
                        }
                        else
                        {
                            cert = new X509Certificate2(certFile, "", importFlags);
                        }
                        _certs.Add(cert);
                    }
                    catch(CryptographicException ex)
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                        e.reason = "IceSSL: error while attempting to load certificate from " + certFile;
                        throw e;
                    }
                }
                else if(findCert.Length > 0)
                {
                    string certStore = properties.getPropertyWithDefault("IceSSL.CertStore", "My");
                    _certs.AddRange(findCertificates("IceSSL.FindCert", storeLocation, certStore, findCert));
                    if(_certs.Count == 0)
                    {
                        throw new Ice.PluginInitializationException("IceSSL: no certificates found");
                    }
                }
                else if(findCertProps.Count > 0)
                {
                    //
                    // If IceSSL.FindCert.* properties are defined, add the selected certificates
                    // to the collection.
                    //
                    foreach(KeyValuePair<string, string> entry in findCertProps)
                    {
                        string name = entry.Key;
                        string val = entry.Value;
                        if(val.Length > 0)
                        {
                            string storeSpec = name.Substring(findPrefix.Length);
                            StoreLocation storeLoc = 0;
                            StoreName storeName = 0;
                            string sname = null;
                            parseStore(name, storeSpec, ref storeLoc, ref storeName, ref sname);
                            if(sname == null)
                            {
                                sname = storeName.ToString();
                            }
                            X509Certificate2Collection coll = findCertificates(name, storeLoc, sname, val);
                            _certs.AddRange(coll);
                        }
                    }
                    if(_certs.Count == 0)
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                        e.reason = "IceSSL: no certificates found";
                        throw e;
                    }
                }
            }

            if(_caCerts == null)
            {
                string certAuthFile = properties.getProperty(prefix + "CAs");
                if(certAuthFile.Length == 0)
                {
                    certAuthFile = properties.getProperty(prefix + "CertAuthFile");
                }
                if(certAuthFile.Length > 0 || properties.getPropertyAsInt(prefix + "UsePlatformCAs") <= 0)
                {
                    _caCerts = new X509Certificate2Collection();
                }
                if(certAuthFile.Length > 0)
                {
                    if(!checkPath(ref certAuthFile))
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                        e.reason = "IceSSL: CA certificate file not found: " + certAuthFile;
                        throw e;
                    }

                    try
                    {
                        using(System.IO.FileStream fs = System.IO.File.OpenRead(certAuthFile))
                        {
                            byte[] data = new byte[fs.Length];
                            fs.Read(data, 0, data.Length);

                            string strbuf = "";
                            try
                            {
                                strbuf = System.Text.Encoding.UTF8.GetString(data);
                            }
                            catch(Exception)
                            {
                                // Ignore
                            }

                            if(strbuf.Length == data.Length)
                            {
                                int size, startpos, endpos = 0;
                                bool first = true;
                                while(true)
                                {
                                    startpos = strbuf.IndexOf("-----BEGIN CERTIFICATE-----", endpos);
                                    if(startpos != -1)
                                    {
                                        endpos = strbuf.IndexOf("-----END CERTIFICATE-----", startpos);
                                        size = endpos - startpos + "-----END CERTIFICATE-----".Length;
                                    }
                                    else if(first)
                                    {
                                        startpos = 0;
                                        endpos = strbuf.Length;
                                        size = strbuf.Length;
                                    }
                                    else
                                    {
                                        break;
                                    }

                                    byte[] cert = new byte[size];
                                    System.Buffer.BlockCopy(data, startpos, cert, 0, size);
                                    _caCerts.Import(cert);
                                    first = false;
                                }
                            }
                            else
                            {
                                _caCerts.Import(data);
                            }
                        }
                    }
                    catch(Exception ex)
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                        e.reason = "IceSSL: error while attempting to load CA certificate from " + certAuthFile;
                        throw e;
                    }
                }
            }
#endif

            _initialized = true;
        }
コード例 #9
0
ファイル: CertificateDialog.cs プロジェクト: renyh1013/dp2
        private static X509Certificate2 PickCertificate()
        {
            X509Certificate2Collection collection = new X509Certificate2Collection();
            X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);

            collection.AddRange(store.Certificates);
#if NO
            store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);

            collection.AddRange(store.Certificates);
#endif
            try
            {

                // pick a certificate from the store

                X509Certificate2Collection selected =
                    X509Certificate2UI.SelectFromCollection(
                         collection,
                         "受信任的根证书",
                         "请选择一个证书:",
                         X509SelectionFlag.SingleSelection);

                if (selected.Count == 0)
                    return null;

                return selected[0];

                /*
                X509Certificate2 cert =
                // show certificate details dialog
                X509Certificate2UI.DisplayCertificate(cert);
                 * */
            }
            finally
            {
                store.Close();
            }
        }
コード例 #10
0
ファイル: RSA.cs プロジェクト: FOGProject/zazzles
        /// <summary>
        /// Build a certificate list containing all certificates needed to perform a chain validate of the {cert} param
        /// </summary>
        /// <param name="cert">The certificate that needs to be validated</param>
        /// <param name="store">An opened X509Store to extract keys from</param>
        /// <return></return>
        private static X509Certificate2Collection BuildCertChainStore(X509Certificate2 cert, X509Store store)
        {
            if (cert == null)
                throw new ArgumentNullException(nameof(cert));
            if (store == null)
                throw new ArgumentNullException(nameof(store));

            var collection = new X509Certificate2Collection();

            // Calculate which certificate issued the given {cert} param
            // Do this by extracting the Authority Key Identifier and searching
            // the store for certificates with an identical Subject Key Identifier
            // For all matches (though there should only be one), repeat the process
            // until no matches are found. This will ensure certificates for the entire
            // chain are selected
            var authorityKey = ExtractX509Extension(cert, OidAuthorityKeyIdentifier);
            var matches = store.Certificates.Find(X509FindType.FindBySubjectKeyIdentifier, authorityKey.RawData, true);
            foreach (var match in matches)
            {
                collection.Add(match);
                collection.AddRange(BuildCertChainStore(match, store));
            }

            return collection;
        }
コード例 #11
0
 private X509Certificate2Collection BuildBagOfCerts()
 {
     X509Certificate2Collection certificates = new X509Certificate2Collection();
     if (this.KeyInfo != null)
     {
         foreach (KeyInfoClause clause in this.KeyInfo)
         {
             KeyInfoX509Data data = clause as KeyInfoX509Data;
             if (data != null)
             {
                 certificates.AddRange(System.Security.Cryptography.Xml.Utils.BuildBagOfCerts(data, CertUsageType.Verification));
             }
         }
     }
     return certificates;
 }
コード例 #12
0
ファイル: Certificates.cs プロジェクト: dstrucl/Tangenta40
        private X509Certificate2Collection findAllCertificatesInAllStores(IList<X509Store> stores, Func<X509Store, X509Certificate2Collection> searchAction)
        {
            X509Certificate2Collection matchingCertificates = new X509Certificate2Collection();

              foreach (var store in stores)
            matchingCertificates.AddRange(this.findAllCertificatesInStore(store, searchAction));

              return matchingCertificates;
        }
コード例 #13
0
ファイル: EnvelopedCms.cs プロジェクト: scholtz/FastZep
 private static SafeCertStoreHandle BuildOriginatorStore(X509Certificate2Collection bagOfCerts, X509Certificate2Collection extraStore)
 {
     X509Certificate2Collection collection = new X509Certificate2Collection();
     try
     {
         X509Store x509Store = new X509Store("AddressBook", StoreLocation.CurrentUser);
         x509Store.Open(OpenFlags.OpenExistingOnly | OpenFlags.IncludeArchived);
         collection.AddRange(x509Store.Certificates);
     }
     catch (SecurityException ex)
     {
     }
     try
     {
         X509Store x509Store = new X509Store("AddressBook", StoreLocation.LocalMachine);
         x509Store.Open(OpenFlags.OpenExistingOnly | OpenFlags.IncludeArchived);
         collection.AddRange(x509Store.Certificates);
     }
     catch (SecurityException ex)
     {
     }
     if (bagOfCerts != null)
         collection.AddRange(bagOfCerts);
     if (extraStore != null)
         collection.AddRange(extraStore);
     if (collection.Count == 0)
         throw new CryptographicException(-2146885628);
     else
         return X509Utils.ExportToMemoryStore(collection);
 }
コード例 #14
0
ファイル: Instance.cs プロジェクト: sbesson/zeroc-ice
        private X509Certificate2Collection findCertificates(string prop, string storeSpec, string value)
        {
            StoreLocation storeLoc = 0;
            StoreName storeName = 0;
            string storeNameStr = null;
            parseStore(prop, storeSpec, ref storeLoc, ref storeName, ref storeNameStr);

            //
            // Open the X509 certificate store.
            //
            X509Store store = null;
            try
            {
                if(storeNameStr != null)
                {
                    store = new X509Store(storeNameStr, storeLoc);
                }
                else
                {
                    store = new X509Store(storeName, storeLoc);
                }
                store.Open(OpenFlags.ReadOnly);
            }
            catch(Exception ex)
            {
                Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                e.reason = "IceSSL: failure while opening store specified by " + prop;
                throw e;
            }

            //
            // Start with all of the certificates in the collection and filter as necessary.
            //
            // - If the value is "*", return all certificates.
            // - Otherwise, search using key:value pairs. The following keys are supported:
            //
            //   Issuer
            //   IssuerDN
            //   Serial
            //   Subject
            //   SubjectDN
            //   SubjectKeyId
            //   Thumbprint
            //
            //   A value must be enclosed in single or double quotes if it contains whitespace.
            //
            X509Certificate2Collection result = new X509Certificate2Collection();
            result.AddRange(store.Certificates);
            try
            {
                if(value != "*")
                {
                    int start = 0;
                    int pos;
                    while((pos = value.IndexOf(':', start)) != -1)
                    {
                        //
                        // Parse the X509FindType.
                        //
                        string field = value.Substring(start, pos - start).Trim().ToUpperInvariant();
                        X509FindType findType;
                        if(field.Equals("SUBJECT"))
                        {
                            findType = X509FindType.FindBySubjectName;
                        }
                        else if(field.Equals("SUBJECTDN"))
                        {
                            findType = X509FindType.FindBySubjectDistinguishedName;
                        }
                        else if(field.Equals("ISSUER"))
                        {
                            findType = X509FindType.FindByIssuerName;
                        }
                        else if(field.Equals("ISSUERDN"))
                        {
                            findType = X509FindType.FindByIssuerDistinguishedName;
                        }
                        else if(field.Equals("THUMBPRINT"))
                        {
                            findType = X509FindType.FindByThumbprint;
                        }
                        else if(field.Equals("SUBJECTKEYID"))
                        {
                            findType = X509FindType.FindBySubjectKeyIdentifier;
                        }
                        else if(field.Equals("SERIAL"))
                        {
                            findType = X509FindType.FindBySerialNumber;
                        }
                        else
                        {
                            Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                            e.reason = "IceSSL: unknown key in `" + value + "'";
                            throw e;
                        }

                        //
                        // Parse the argument.
                        //
                        start = pos + 1;
                        while(start < value.Length && (value[start] == ' ' || value[start] == '\t'))
                        {
                            ++start;
                        }
                        if(start == value.Length)
                        {
                            Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                            e.reason = "IceSSL: missing argument in `" + value + "'";
                            throw e;
                        }

                        string arg;
                        if(value[start] == '"' || value[start] == '\'')
                        {
                            int end = start;
                            ++end;
                            while(end < value.Length)
                            {
                                if(value[end] == value[start] && value[end - 1] != '\\')
                                {
                                    break;
                                }
                                ++end;
                            }
                            if(end == value.Length || value[end] != value[start])
                            {
                                Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                                e.reason = "IceSSL: unmatched quote in `" + value + "'";
                                throw e;
                            }
                            ++start;
                            arg = value.Substring(start, end - start);
                            start = end + 1;
                        }
                        else
                        {
                            char[] ws = new char[] { ' ', '\t' };
                            int end = value.IndexOfAny(ws, start);
                            if(end == -1)
                            {
                                arg = value.Substring(start);
                                start = value.Length;
                            }
                            else
                            {
                                arg = value.Substring(start, end - start);
                                start = end + 1;
                            }
                        }

                        //
                        // Execute the query.
                        //
                        // TODO: allow user to specify a value for validOnly?
                        //
                        bool validOnly = false;
                        result = result.Find(findType, arg, validOnly);
                    }
                }
            }
            finally
            {
                store.Close();
            }

            return result;
        }
コード例 #15
0
ファイル: PkcsUtils.cs プロジェクト: JianwenSun/cc
        internal static X509Certificate2Collection CreateBagOfCertificates (CmsSigner signer) {
            X509Certificate2Collection certificates = new X509Certificate2Collection();

            //
            // First add extra bag of certs.
            //

            certificates.AddRange(signer.Certificates);

            //
            // Then include chain option.
            //

            if (signer.IncludeOption != X509IncludeOption.None) {
                if (signer.IncludeOption == X509IncludeOption.EndCertOnly) {
                    certificates.Add(signer.Certificate);
                }
                else {
                    int cCerts = 1;
                    X509Chain chain = new X509Chain();
                    chain.Build(signer.Certificate);

                    // Can't honor the option if we only have a partial chain.
                    if ((chain.ChainStatus.Length > 0) && 
                        ((chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain))
                        throw new CryptographicException(CAPI.CERT_E_CHAINING);

                    if (signer.IncludeOption == X509IncludeOption.WholeChain) {
                        cCerts = chain.ChainElements.Count;
                    }
                    else {
                        // Default to ExcludeRoot.
                        if (chain.ChainElements.Count > 1) {
                            cCerts = chain.ChainElements.Count - 1;
                        }
                    }

                    for (int i = 0; i < cCerts; i++) {
                        certificates.Add(chain.ChainElements[i].Certificate);
                    }
                }
            }

            return certificates;
        }
コード例 #16
0
ファイル: EnvelopedPkcs7.cs プロジェクト: JianwenSun/cc
        private static SafeCertStoreHandle BuildOriginatorStore (X509Certificate2Collection bagOfCerts, X509Certificate2Collection extraStore) {
            // Build store where to find originator's certificate.
            X509Certificate2Collection originatorStore = new X509Certificate2Collection();

            // Include CU and LM MY stores.
            try {
                X509Store cuMy = new X509Store("AddressBook", StoreLocation.CurrentUser);
                cuMy.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly | OpenFlags.IncludeArchived);
                originatorStore.AddRange(cuMy.Certificates);

            }
            catch (SecurityException) {
                // X509Store.Open() may not have permission. Ignore.
            }
            try {
                X509Store lmMy = new X509Store("AddressBook", StoreLocation.LocalMachine);
                lmMy.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly | OpenFlags.IncludeArchived);
                originatorStore.AddRange(lmMy.Certificates);
            }
            catch (SecurityException) {
                // Ignore. May be in bag of certs or extra store.
            }

            // Finally, include bag of certs and extra store, if specified.
            if (bagOfCerts != null) {
                originatorStore.AddRange(bagOfCerts);
            }
            if (extraStore != null) {
                originatorStore.AddRange(extraStore);
            }

            if (originatorStore.Count == 0)
                throw new CryptographicException(CAPI.CRYPT_E_NOT_FOUND);

            // Return memory store handle.
            return X509Utils.ExportToMemoryStore(originatorStore);
        }
コード例 #17
0
ファイル: EnvelopedCms.cs プロジェクト: ESgarbi/corefx
        private void DecryptContent(RecipientInfoCollection recipientInfos, X509Certificate2Collection extraStore)
        {
            switch (_lastCall)
            {
                case LastCall.Ctor:
                    throw new InvalidOperationException(SR.Cryptography_Cms_MessageNotEncrypted);

                case LastCall.Encrypt:
                    throw PkcsPal.Instance.CreateDecryptAfterEncryptException();

                case LastCall.Decrypt:
                    throw PkcsPal.Instance.CreateDecryptTwiceException();

                case LastCall.Decode:
                    break; // This is the expected state.

                default:
                    Debug.Fail($"Unexpected _lastCall value: {_lastCall}");
                    throw new InvalidOperationException();
            }

            extraStore = extraStore ?? new X509Certificate2Collection();

            X509Certificate2Collection certs = new X509Certificate2Collection();
            PkcsPal.Instance.AddCertsFromStoreForDecryption(certs);
            certs.AddRange(extraStore);

            X509Certificate2Collection originatorCerts = Certificates;

            ContentInfo newContentInfo = null;
            Exception exception = PkcsPal.Instance.CreateRecipientsNotFoundException();
            foreach (RecipientInfo recipientInfo in recipientInfos)
            {
                X509Certificate2 cert = certs.TryFindMatchingCertificate(recipientInfo.RecipientIdentifier);
                if (cert == null)
                {
                    exception = PkcsPal.Instance.CreateRecipientsNotFoundException();
                    continue;
                }
                newContentInfo = _decryptorPal.TryDecrypt(recipientInfo, cert, originatorCerts, extraStore, out exception);
                if (exception != null)
                    continue;

                break;
            }

            if (exception != null)
                throw exception;

            ContentInfo = newContentInfo;

            // Desktop compat: Encode() after a Decrypt() returns you the same thing that ContentInfo.Content does.
            _encodedMessage = newContentInfo.Content.CloneByteArray();

            _lastCall = LastCall.Decrypt;
        }
コード例 #18
0
ファイル: signedxml.cs プロジェクト: mind0n/hive
        private X509Certificate2Collection BuildBagOfCerts () {
            X509Certificate2Collection collection = new X509Certificate2Collection();
            if (this.KeyInfo != null) {
                foreach (KeyInfoClause clause in this.KeyInfo) {
                    KeyInfoX509Data x509Data = clause as KeyInfoX509Data;
                    if (x509Data != null) 
                        collection.AddRange(Utils.BuildBagOfCerts(x509Data, CertUsageType.Verification));
                }
            }

            return collection;
        }
コード例 #19
0
ファイル: SmtpClient.cs プロジェクト: KiransHub/OpaqueMail
        /// <summary>
        /// Helper function to look up and validate public keys for each recipient.
        /// </summary>
        /// <param name="message">An OpaqueMail.MailMessage that contains the message to send.</param>
        /// <param name="addressesWithPublicKeys">Collection containing recipients with valid public keys.</param>
        /// <param name="addressesNeedingPublicKeys">Collection containing recipients without valid public keys.</param>
        private void ResolvePublicKeys(MailMessage message, out HashSet<string> addressesWithPublicKeys, out Dictionary<string, MailAddress> addressesNeedingPublicKeys)
        {
            // Initialize collections for all recipients.
            addressesWithPublicKeys = new HashSet<string>();
            addressesNeedingPublicKeys = new Dictionary<string, MailAddress>();

            MailAddressCollection[] addressRanges = new MailAddressCollection[] { message.To, message.CC, message.Bcc };
            foreach (MailAddressCollection addressRange in addressRanges)
            {
                foreach (MailAddress toAddress in addressRange)
                {
                    string canonicalToAddress = toAddress.Address.ToUpper();
                    if (SmimeCertificateCache.ContainsKey(canonicalToAddress))
                    {
                        if (!addressesWithPublicKeys.Contains(canonicalToAddress))
                            addressesWithPublicKeys.Add(canonicalToAddress);
                    }
                    else
                    {
                        if (!addressesNeedingPublicKeys.ContainsKey(canonicalToAddress))
                            addressesNeedingPublicKeys.Add(canonicalToAddress, toAddress);
                    }
                }
            }

            // If any addresses haven't been mapped to public keys, map them.
            if (addressesNeedingPublicKeys.Count > 0)
            {
                // Read from the Windows certificate store if valid certificates aren't specified.
                if (SmimeValidCertificates == null || SmimeValidCertificates.Count < 1)
                {
                    // Load from the current user.
                    X509Store store = new X509Store(StoreLocation.CurrentUser);
                    store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
                    SmimeValidCertificates = store.Certificates;
                    store.Close();

                    // Add any tied to the local machine.
                    store = new X509Store(StoreLocation.LocalMachine);
                    store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
                    SmimeValidCertificates.AddRange(store.Certificates);
                    store.Close();
                }

                // Loop through certificates and check for matching recipients.
                foreach (X509Certificate2 cert in SmimeValidCertificates)
                {
                    // Look at certificates with e-mail subject names.
                    string canonicalCertSubject = "";
                    if (cert.Subject.StartsWith("E="))
                        canonicalCertSubject = cert.Subject.Substring(2).ToUpper();
                    else if (cert.Subject.StartsWith("CN="))
                        canonicalCertSubject = cert.Subject.Substring(3).ToUpper();
                    else
                        canonicalCertSubject = cert.Subject.ToUpper();

                    int certSubjectComma = canonicalCertSubject.IndexOf(",");
                    if (certSubjectComma > -1)
                        canonicalCertSubject = canonicalCertSubject.Substring(0, certSubjectComma);

                    // Only proceed if the key is for a recipient of this e-mail.
                    if (!addressesNeedingPublicKeys.ContainsKey(canonicalCertSubject))
                        continue;

                    // Verify the certificate chain.
                    if ((message.SmimeEncryptionOptionFlags & SmimeEncryptionOptionFlags.RequireCertificateVerification) > 0)
                    {
                        if (!cert.Verify())
                            continue;
                    }

                    // Ensure valid key usage scenarios.
                    if ((message.SmimeEncryptionOptionFlags & SmimeEncryptionOptionFlags.RequireKeyUsageOfDataEncipherment) > 0 || (message.SmimeEncryptionOptionFlags & SmimeEncryptionOptionFlags.RequireEnhancedKeyUsageofSecureEmail) > 0)
                    {
                        bool keyDataEncipherment = false, enhancedKeySecureEmail = false;
                        foreach (X509Extension extension in cert.Extensions)
                        {
                            if (!keyDataEncipherment && extension.Oid.FriendlyName == "Key Usage")
                            {
                                X509KeyUsageExtension ext = (X509KeyUsageExtension)extension;
                                if ((ext.KeyUsages & X509KeyUsageFlags.DataEncipherment) != X509KeyUsageFlags.None)
                                {
                                    keyDataEncipherment = true;

                                    if (!((message.SmimeEncryptionOptionFlags & SmimeEncryptionOptionFlags.RequireEnhancedKeyUsageofSecureEmail) > 0))
                                        break;
                                }
                            }
                            if (!enhancedKeySecureEmail && extension.Oid.FriendlyName == "Enhanced Key Usage")
                            {
                                X509EnhancedKeyUsageExtension ext = (X509EnhancedKeyUsageExtension)extension;
                                OidCollection oids = ext.EnhancedKeyUsages;
                                foreach (Oid oid in oids)
                                {
                                    if (oid.FriendlyName == "Secure Email")
                                    {
                                        enhancedKeySecureEmail = true;
                                        break;
                                    }
                                }
                            }
                        }
                        if ((message.SmimeEncryptionOptionFlags & SmimeEncryptionOptionFlags.RequireKeyUsageOfDataEncipherment) > 0 && !keyDataEncipherment)
                            continue;
                        if ((message.SmimeEncryptionOptionFlags & SmimeEncryptionOptionFlags.RequireEnhancedKeyUsageofSecureEmail) > 0 && !enhancedKeySecureEmail)
                            continue;
                    }

                    // If we've made it this far, we can use the certificate for a recipient.
                    MailAddress originalAddress = addressesNeedingPublicKeys[canonicalCertSubject];
                    SmimeCertificateCache.Add(canonicalCertSubject, cert);
                    addressesWithPublicKeys.Add(canonicalCertSubject);
                    addressesNeedingPublicKeys.Remove(canonicalCertSubject);

                    // Shortcut to abort processing of additional certificates if all recipients are accounted for.
                    if (addressesNeedingPublicKeys.Count < 1)
                        break;
                }
            }
        }
コード例 #20
0
ファイル: utils.cs プロジェクト: mind0n/hive
        internal static X509Certificate2Collection BuildBagOfCerts (KeyInfoX509Data keyInfoX509Data, CertUsageType certUsageType) {
            X509Certificate2Collection collection = new X509Certificate2Collection();
            ArrayList decryptionIssuerSerials = (certUsageType == CertUsageType.Decryption ? new ArrayList() : null);
            if (keyInfoX509Data.Certificates != null) {
                foreach (X509Certificate2 certificate in keyInfoX509Data.Certificates) {
                    switch (certUsageType) {
                    case CertUsageType.Verification:
                        collection.Add(certificate);
                        break;
                    case CertUsageType.Decryption:
                        decryptionIssuerSerials.Add(new X509IssuerSerial(certificate.IssuerName.Name, certificate.SerialNumber));
                        break;
                    }
                }
            }

            if (keyInfoX509Data.SubjectNames == null && keyInfoX509Data.IssuerSerials == null &&
                keyInfoX509Data.SubjectKeyIds == null && decryptionIssuerSerials == null)
                return collection;

            // Open LocalMachine and CurrentUser "Other People"/"My" stores.

            // Assert OpenStore since we are not giving back any certificates to the user.
            StorePermission sp = new StorePermission(StorePermissionFlags.OpenStore);
            sp.Assert();

            X509Store[] stores = new X509Store[2];
            string storeName = (certUsageType == CertUsageType.Verification ? "AddressBook" : "My");
            stores[0] = new X509Store(storeName, StoreLocation.CurrentUser);
            stores[1] = new X509Store(storeName, StoreLocation.LocalMachine);

            for (int index=0; index < stores.Length; index++) {
                if (stores[index] != null) {
                    X509Certificate2Collection filters = null;
                    // We don't care if we can't open the store.
                    try {
                        stores[index].Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                        filters = stores[index].Certificates;
                        stores[index].Close();
                        if (keyInfoX509Data.SubjectNames != null) {
                            foreach (string subjectName in keyInfoX509Data.SubjectNames) {
                                filters = filters.Find(X509FindType.FindBySubjectDistinguishedName, subjectName, false);
                            }
                        }
                        if (keyInfoX509Data.IssuerSerials != null) {
                            foreach (X509IssuerSerial issuerSerial in keyInfoX509Data.IssuerSerials) {
                                filters = filters.Find(X509FindType.FindByIssuerDistinguishedName, issuerSerial.IssuerName, false);
                                filters = filters.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false);
                            }
                        }
                        if (keyInfoX509Data.SubjectKeyIds != null) {
                            foreach (byte[] ski in keyInfoX509Data.SubjectKeyIds) {
                                string hex = X509Utils.EncodeHexString(ski);
                                filters = filters.Find(X509FindType.FindBySubjectKeyIdentifier, hex, false);
                            }
                        }
                        if (decryptionIssuerSerials != null) {
                            foreach (X509IssuerSerial issuerSerial in decryptionIssuerSerials) {
                                filters = filters.Find(X509FindType.FindByIssuerDistinguishedName, issuerSerial.IssuerName, false);
                                filters = filters.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false);
                            }
                        }
                    }
                    catch (CryptographicException) {}

                    if (filters != null) 
                        collection.AddRange(filters);
                }
            }

            return collection;
        }
コード例 #21
0
		public void AddRange_X509Certificate2Collection ()
		{
			X509Certificate2Collection c = new X509Certificate2Collection ();
			c.AddRange (empty);
			Assert.AreEqual (0, c.Count, "0");
			c.AddRange (single);
			Assert.AreEqual (1, c.Count, "1");
			c.AddRange (collection);
			Assert.AreEqual (3, c.Count, "3");
			// re-adding same collection
			c.AddRange (single);
			Assert.AreEqual (4, c.Count, "4");
		}
コード例 #22
0
ファイル: AsyncSocket.cs プロジェクト: sq5gvm/JabberNet-2010
        /// <summary>
        /// Choose a certificate from the local store.  If there are
        /// none available, returns right away.
        /// If there is exactly one, uses it.
        /// Otherwise, prompts.
        /// TODO: figure out something for server certs, too.
        /// </summary>
        /// <param name="acceptableIssuers">A list of DNs of CAs that are trusted by the other party</param>
        public void ChooseClientCertificate(string[] acceptableIssuers)
        {
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection coll = new X509Certificate2Collection();
            if (acceptableIssuers == null)
            {
                coll.AddRange(store.Certificates);
            }
            else
            {
                foreach (X509Certificate2 cert in store.Certificates)
                {
                    foreach (string issuer in acceptableIssuers)
                    {
                        if (cert.Issuer == issuer)
                        {
                            coll.Add(cert);
                        }
                    }
                }
            }

            switch (coll.Count)
            {
                case 0:
                    return;
                case 1:
                    m_cert = coll[0];
                    return;
                default:
#if __MonoCS__
                        m_cert = null;
#else
                    X509Certificate2Collection certs = X509Certificate2UI.SelectFromCollection(
                        coll,
                        "Select certificate",
                        "Use this certificate to log in",
                        X509SelectionFlag.SingleSelection);
                    if (certs.Count > 0)
                        m_cert = certs[0];
#endif
                    break;
            }
        }
コード例 #23
0
		public void AddRange_X509Certificate2Array ()
		{
			X509Certificate2Collection c = new X509Certificate2Collection ();
			c.AddRange (new X509Certificate2 [0]);
			Assert.AreEqual (0, c.Count, "0");
			c.AddRange (new X509Certificate2[3] { cert1, cert2, cert_empty });
			Assert.AreEqual (3, c.Count, "3");
		}
コード例 #24
0
        public void CopyTo(X509Certificate2Collection collection)
        {
            Debug.Assert(collection != null);

            collection.AddRange(_certs);
        }
コード例 #25
0
        private Exception TryDecryptAgree(KeyAgreeRecipientInfo keyAgreeRecipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore)
        {
            unsafe
            {
                KeyAgreeRecipientInfoPalWindows pal = (KeyAgreeRecipientInfoPalWindows)(keyAgreeRecipientInfo.Pal);
                return pal.WithCmsgCmsRecipientInfo<Exception>(
                    delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* pKeyAgreeRecipientInfo)
                    {
                        CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara = default(CMSG_CTRL_KEY_AGREE_DECRYPT_PARA);
                        decryptPara.cbSize = Marshal.SizeOf<CMSG_CTRL_KEY_AGREE_DECRYPT_PARA>();
                        decryptPara.hProv = hKey;
                        decryptPara.dwKeySpec = keySpec;
                        decryptPara.pKeyAgree = pKeyAgreeRecipientInfo;
                        decryptPara.dwRecipientIndex = pal.Index;
                        decryptPara.dwRecipientEncryptedKeyIndex = pal.SubIndex;
                        CMsgKeyAgreeOriginatorChoice originatorChoice = pKeyAgreeRecipientInfo->dwOriginatorChoice;
                        switch (originatorChoice)
                        {
                            case CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_CERT:
                                {
                                    X509Certificate2Collection candidateCerts = new X509Certificate2Collection();
                                    candidateCerts.AddRange(Helpers.GetStoreCertificates(StoreName.AddressBook, StoreLocation.CurrentUser, openExistingOnly: true));
                                    candidateCerts.AddRange(Helpers.GetStoreCertificates(StoreName.AddressBook, StoreLocation.LocalMachine, openExistingOnly: true));
                                    candidateCerts.AddRange(originatorCerts);
                                    candidateCerts.AddRange(extraStore);
                                    SubjectIdentifier originatorId = pKeyAgreeRecipientInfo->OriginatorCertId.ToSubjectIdentifier();
                                    using (X509Certificate2 originatorCert = candidateCerts.TryFindMatchingCertificate(originatorId))
                                    {
                                        if (originatorCert == null)
                                            return ErrorCode.CRYPT_E_NOT_FOUND.ToCryptographicException();
                                        using (SafeCertContextHandle hCertContext = originatorCert.CreateCertContextHandle())
                                        {
                                            CERT_CONTEXT* pOriginatorCertContext = hCertContext.DangerousGetCertContext();
                                            decryptPara.OriginatorPublicKey = pOriginatorCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey;

                                            // Do not factor this call out of the switch statement as leaving this "using" block will free up
                                            // native memory that decryptPara points to. 
                                            return TryExecuteDecryptAgree(ref decryptPara);
                                        }
                                    }
                                }

                            case CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_PUBLIC_KEY:
                                {
                                    decryptPara.OriginatorPublicKey = pKeyAgreeRecipientInfo->OriginatorPublicKeyInfo.PublicKey;
                                    return TryExecuteDecryptAgree(ref decryptPara);
                                }

                            default:
                                return new CryptographicException(SR.Format(SR.Cryptography_Cms_Invalid_Originator_Identifier_Choice, originatorChoice));
                        }
                    });
            }
        }
コード例 #26
0
        public bool DestroySignedCertificates()
        {
            var myCertificates = new X509Certificate2Collection();
            var rootCertificates = new X509Certificate2Collection();
            try
            {
                lock (MyStore)
                {
                    MyStore.Open(OpenFlags.ReadWrite);

                    var myStoreCertificates = MyStore.Certificates
                        .Find(X509FindType.FindByIssuerName, Issuer, false);

                    myCertificates.AddRange(myStoreCertificates);
                }
                lock (RootStore)
                {
                    RootStore.Open(OpenFlags.ReadWrite);

                    var myRootCertificates = RootStore.Certificates
                        .Find(X509FindType.FindByIssuerName, Issuer, false);

                    rootCertificates.AddRange(myRootCertificates);
                }
                return DestroySignedCertificates(myCertificates, rootCertificates);
            }
            finally
            {
                MyStore.Close();
                RootStore.Close();
            }
        }
コード例 #27
0
ファイル: PkcsPalWindows.cs プロジェクト: ESgarbi/corefx
 public sealed override void AddCertsFromStoreForDecryption(X509Certificate2Collection certs)
 {
     certs.AddRange(Helpers.GetStoreCertificates(StoreName.My, StoreLocation.CurrentUser, openExistingOnly: true));
     certs.AddRange(Helpers.GetStoreCertificates(StoreName.My, StoreLocation.LocalMachine, openExistingOnly: true));
 }