Add() public method

public Add ( System certificate ) : int
certificate System
return int
Example #1
0
		public void FixtureSetUp ()
		{
			cert_empty = new X509Certificate2 ();
			cert1 = new X509Certificate2 (X509Certificate2Test.farscape_pfx, "farscape", X509KeyStorageFlags.Exportable);
			cert2 = new X509Certificate2 (Encoding.ASCII.GetBytes (X509Certificate2Test.base64_cert));

			//empty = new X509Certificate2Collection ();
			collection = new X509Certificate2Collection ();
			collection.Add (cert1);
			collection.Add (cert2);
		}
 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;
 }
Example #3
0
        public static X509Certificate2 PickCertificate()
        {
            var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
            var collection = store.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
            var gostOnlyCollection = new X509Certificate2Collection();

            foreach ( var cert in collection.Cast<X509Certificate2>()
                        .Where(cert => cert.SignatureAlgorithm.Value.Equals("1.2.643.2.2.3")))
                gostOnlyCollection.Add(cert);

            if (gostOnlyCollection.Count == 0)
                throw new ApplicationException("Не найдено ни одной подписи соответствующей ГОСТ Р 34.11/34.10-2001. \n");

            var found = X509Certificate2UI.SelectFromCollection(
                    gostOnlyCollection,
                    "Выберите сертификат",
                    "Выбранная ЭЦП будет использована при подписании файла, и является эквивалентом собственноручной подписи либо печати организации",
                    X509SelectionFlag.SingleSelection
                );

            if (found.Count == 0)
            {
                throw new ApplicationException("Сертификат не выбран.\n");
            }

            if (found.Count > 1)
            {
                throw new ApplicationException("Найдено больше одного сертификата.\n");
            }

            return found[0];
        }
        public static void Rc4AndCngWrappersDontMixTest()
        {
            //
            // Combination of RC4 over a CAPI certificate.
            //
            //  This works as long as the PKCS implementation opens the cert using CAPI. If he creates a CNG wrapper handle (by passing CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG),
            //  the test fails with a NOTSUPPORTED crypto exception inside Decrypt(). The same happens if the key is genuinely CNG.
            //

            byte[] content = { 6, 3, 128, 33, 44 };
            AlgorithmIdentifier rc4 = new AlgorithmIdentifier(new Oid(Oids.Rc4));

            EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(content), rc4);
            CmsRecipientCollection recipients = new CmsRecipientCollection(new CmsRecipient(Certificates.RSAKeyTransferCapi1.GetCertificate()));
            ecms.Encrypt(recipients);
            byte[] encodedMessage = ecms.Encode();

            ecms = new EnvelopedCms();
            ecms.Decode(encodedMessage);

            using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
            {
                if (cert == null)
                    return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can.

                X509Certificate2Collection extraStore = new X509Certificate2Collection();
                extraStore.Add(cert);
                ecms.Decrypt(extraStore);
            }

            ContentInfo contentInfo = ecms.ContentInfo;
            Assert.Equal<byte>(content, contentInfo.Content);
        }
        /// <summary>
        /// Initialisiert eine neue Instanz der <see cref="ReceiverCertificates"/> Klasse.
        /// </summary>
        /// <param name="certificates">Die Empfänger-Zertifikate</param>
        public ReceiverCertificates(IReadOnlyCollection<X509Certificate2> certificates)
        {
            var receiverCertificates = new Dictionary<string, X509Certificate2>();
            var rootCertificates = new List<X509Certificate2>();
            var intermediateCertificates = new X509Certificate2Collection();
            foreach (var certificate in certificates)
            {
                var key = GetKey(certificate);
                if (key == null)
                {
                    if (certificate.SubjectName.Name == certificate.IssuerName.Name)
                    {
                        rootCertificates.Add(certificate);
                    }
                    else
                    {
                        intermediateCertificates.Add(certificate);
                    }
                }
                else
                {
                    receiverCertificates.Add(key, certificate);
                }
            }

            _rootCertificates = rootCertificates.ToArray();
            _intermediateCertificates = intermediateCertificates;
            Certificates = receiverCertificates;
        }
        public void SendEmptyPushNotification(string deviceIdentifier, string thumbprint)
        {
            string server = "gateway.push.apple.com";
            using (TcpClient tcpClient = new TcpClient(server, 2195))
            {
                Trace.TraceInformation("Opening SSL Connection...");
                using (SslStream sslStream = new SslStream(tcpClient.GetStream()))
                {
                    try
                    {
                        X509Certificate2Collection certs = new X509Certificate2Collection();

                        Trace.TraceInformation("Adding certificate to connection...");
                        X509Certificate cert = GetAppleServerCert(thumbprint);
                        certs.Add(cert);

                        Trace.TraceInformation("Authenticating against the SSL stream...");
                        sslStream.AuthenticateAsClient(server, certs, SslProtocols.Default, false);
                    }
                    catch (AuthenticationException exp)
                    {
                        Trace.TraceError("Failed to authenticate to APNS - {0}", exp.Message);
                        return;
                    }
                    catch (IOException exp)
                    {
                        Trace.TraceError("Failed to connect to APNS - {0}", exp.Message);
                        return;
                    }

                    byte[] buf = new byte[256];
                    MemoryStream ms = new MemoryStream();
                    BinaryWriter bw = new BinaryWriter(ms);
                    bw.Write(new byte[] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32 });

                    byte[] deviceToken = HexToData(deviceIdentifier);
                    bw.Write(deviceToken);
                    
                    string msg = "{}";

                    bw.Write(new byte[] { 0, 2 });
                    bw.Write(msg.ToCharArray());
                    bw.Flush();

                    Trace.TraceInformation("Message sent. Closing stream...");

                    if (sslStream != null)
                    {
                        sslStream.Write(ms.ToArray());
                    }

                    sslStream.Flush();

                    byte[] response = new byte[6];
                    sslStream.Read(response, 0, 6);
                }
            }
        }
Example #7
0
        public bool ConnectToAPNS(PushData objPush)
        {
            try
            {
                string p12Certificate = "WizzDevelopement.p12";
#if DEBUG
                //   p12Certificate = "WizzProductioncert.p12";
#else
                 p12Certificate = "WizzProductioncert.p12";
#endif

                string p12fileName = p12Certificate; string password = "******";


                X509Certificate2Collection certs = new X509Certificate2Collection();

                // Add the Apple cert to our collection
                certs.Add(getServerCert(p12fileName, password));

                string apsHost;

                if (getServerCert(p12fileName, password).ToString().Contains("Production"))
                    apsHost = "gateway.push.apple.com";
                // Port= Convert.ToInt32("2195")
                else
                    apsHost = "gateway.sandbox.push.apple.com";
                TcpClient tcpClient = new TcpClient(apsHost, 2195);
                //  Connect();
                // Create a TCP socket connection to the Apple server on port 2195

                // Create a new SSL stream over the connection
                sslStream = new SslStream(tcpClient.GetStream());

                // Authenticate using the Apple cert
                sslStream.AuthenticateAsClient(apsHost, certs, SslProtocols.Default, false);

                //6455903fb51593b5fb930ab8184e39c5ec83b57503e6589596d463ddb4b1d835

                Int32 messa = objPush.message.Length;
                if (messa < 256)
                {
                    Boolean send = PushMessage(objPush);
                    return send;
                }
                else
                {
                    throw new Exception("Message not exeed 256 character");

                }


            }
            catch (Exception ex)
            {
                return false;
                // throw new Exception(ex.Message);
            }
        }
Example #8
0
        public void MoveTo(X509Certificate2Collection collection)
        {
            Debug.Assert(collection != null);

            ICertificatePal localCert = Interlocked.Exchange(ref _cert, null);
            Debug.Assert(localCert != null);

            collection.Add(new X509Certificate2(localCert));
        }
Example #9
0
		internal static X509Certificate2Collection GetClientCertificates (ClientParameters parameters)
		{
			if (parameters.ClientCertificate == null)
				return null;

			var clientCertificateCollection = new X509Certificate2Collection ();
			var certificate = (X509Certificate2)CertificateProvider.GetCertificate (parameters.ClientCertificate);
			clientCertificateCollection.Add (certificate);

			return clientCertificateCollection;
		}
Example #10
0
        public void CopyTo(X509Certificate2Collection collection)
        {
            Debug.Assert(collection != null);

            SafeCertContextHandle pCertContext = null;
            while (Interop.crypt32.CertEnumCertificatesInStore(_certStore, ref pCertContext))
            {
                X509Certificate2 cert = new X509Certificate2(pCertContext.DangerousGetHandle());
                collection.Add(cert);
            }
        }
        public void CloneTo(X509Certificate2Collection collection)
        {
            Debug.Assert(collection != null);
            Debug.Assert(_certs != null);

            foreach (X509Certificate2 cert in _certs)
            {
                var certPal = (OpenSslX509CertificateReader)cert.Pal;
                collection.Add(new X509Certificate2(certPal.DuplicateHandles()));
            }
        }
Example #12
0
        public static X509Certificate2Collection FilterValidCerts(
            X509Certificate2Collection certs, 
            X509ChainPolicy policy, 
            X509ChainStatusFlags problemFlags,
            Action<Exception> notification)
        {
            var validCerts = new X509Certificate2Collection();
            if (certs == null) return null;
            foreach (var cert in certs)
            {
                X509Chain chainBuilder = new X509Chain();
                chainBuilder.ChainPolicy = policy.Clone();

                try
                {
                    // We're using the system class as a helper to merely build the chain
                    // However, we will review each item in the chain ourselves, because we have our own rules...
                    chainBuilder.Build(cert);
                    X509ChainElementCollection chainElements = chainBuilder.ChainElements;

                    // If we don't have a trust chain, then we obviously have a problem...
                    if (chainElements.IsNullOrEmpty())
                    {
                        notification(new Exception(string.Format("Can't find a trust chain: {0} ", cert.Subject)));
                        return null;
                    }


                    // walk the chain starting at the leaf and see if we hit any issues before the anchor
                    foreach (X509ChainElement chainElement in chainElements)
                    {
                        if (ChainElementHasProblems(chainElement, problemFlags))
                        {
                            //this.NotifyProblem(chainElement);

                            notification(new Exception(string.Format("Chain Element has problem {0}", Summarize(chainElement, problemFlags))));
                            // Whoops... problem with at least one cert in the chain. Stop immediately
                            return null;
                        }
                    }
                }
                catch (Exception ex)
                {
                    //this.NotifyError(certificate, ex);
                    // just eat it and drop out to return null
                    notification(ex);
                    return null;
                }
                validCerts.Add(cert);
            }
            return validCerts;
        }
        /// <summary>
        /// Initializes static members of the <see cref="CertificatesHandler" /> class.
        /// </summary>
        static CertificatesHandler()
        {
            var cacert = System.Text.Encoding.Default.GetString(Payplug.Resource.cacert);
            var rawPemCertificates = new Regex(
                @"-----BEGIN CERTIFICATE-----((?:.*\s)*?)-----END CERTIFICATE-----",
                RegexOptions.Compiled | RegexOptions.Multiline).Matches(cacert);

            certificate2Collection = new X509Certificate2Collection();
            foreach (Match rawPemCertificate in rawPemCertificates)
            {
                certificate2Collection.Add(new X509Certificate2(Convert.FromBase64String(rawPemCertificate.Groups[1].Value)));
            }
        }
Example #14
0
 private void AddAnchorsForBundle(Bundle bundle, X509Certificate2Collection certs)
 {
     try
     {
         X509Certificate2Collection bundleCerts = m_downloader.DownloadCertificates(bundle.Uri);
         if (!bundleCerts.IsNullOrEmpty())
         {
             certs.Add(bundleCerts);
         }
     }
     catch (Exception e)
     {
         this.NotifyError(bundle, e);
     }
 }
        public void SelfSignedTest()
        {
            var chain = new X509Chain();
            var trusted = new X509Certificate2Collection();

            Assert.IsFalse(chain.Build(Certificates.SelfSigned));
            Assert.IsFalse(chain.VerifyWithExtraRoots(Certificates.SelfSigned, trusted));

            trusted.Add(Certificates.SelfSigned);
            Assert.IsTrue(chain.VerifyWithExtraRoots(Certificates.SelfSigned, trusted));
            Assert.IsFalse(chain.Build(Certificates.SelfSigned));

            trusted.Clear();
            Assert.IsFalse(chain.VerifyWithExtraRoots(Certificates.SelfSigned, trusted));
            Assert.IsFalse(chain.Build(Certificates.SelfSigned));
        }
        public void SelfSignedRootTest()
        {
            var chain = new X509Chain();
            var trusted = new X509Certificate2Collection();
            chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

            Assert.IsFalse(chain.Build(Certificates.SignedBySelfSigned));
            Assert.IsFalse(chain.VerifyWithExtraRoots(Certificates.SignedBySelfSigned, trusted));

            trusted.Add(Certificates.SelfSigned);
            Assert.IsTrue(chain.VerifyWithExtraRoots(Certificates.SignedBySelfSigned, trusted));
            Assert.IsFalse(chain.Build(Certificates.SignedBySelfSigned));

            trusted.Clear();
            Assert.IsFalse(chain.VerifyWithExtraRoots(Certificates.SignedBySelfSigned, trusted));
            Assert.IsFalse(chain.Build(Certificates.SignedBySelfSigned));
        }
Example #17
0
            public void CloneTo(X509Certificate2Collection collection)
            {
                HashSet <X509Certificate2> dedupedCerts = new HashSet <X509Certificate2>();

                using (SafeCFArrayHandle identities = Interop.AppleCrypto.KeychainEnumerateIdentities())
                {
                    ReadCollection(identities, dedupedCerts);
                }

                using (SafeCFArrayHandle certs = Interop.AppleCrypto.KeychainEnumerateCerts())
                {
                    ReadCollection(certs, dedupedCerts);
                }

                foreach (X509Certificate2 cert in dedupedCerts)
                {
                    collection.Add(cert);
                }
            }
		internal X509ChainImplBtls (MonoBtlsX509StoreCtx storeCtx)
		{
			this.storeCtx = storeCtx.Copy ();
			this.chain = storeCtx.GetChain ();

			policy = new X509ChainPolicy ();

			untrustedChain = storeCtx.GetUntrusted ();

			if (untrustedChain != null) {
				untrusted = new X509Certificate2Collection ();
				policy.ExtraStore = untrusted;
				for (int i = 0; i < untrustedChain.Count; i++) {
					var cert = untrustedChain.GetCertificate (i);
					using (var impl = new X509CertificateImplBtls (cert))
						untrusted.Add (new X509Certificate2 (impl));
				}
			}
		}
        public async Task<X509Certificate2Collection> GetCertificates()
        {
            X509Certificate2Collection collection = new X509Certificate2Collection();

            CertificateStoreIdentifier id = new CertificateStoreIdentifier();

            id.StoreType = this.StoreType;
            id.StorePath = this.StorePath;

            if (!String.IsNullOrEmpty(id.StorePath))
            {
                try
                {
                    ICertificateStore store = id.OpenStore();

                    try
                    {
                        collection = await store.Enumerate();
                    }
                    finally
                    {
                        store.Close();
                    }
                }
                catch (Exception)
                {
                    Utils.Trace("Could not load certificates from store: {0}.", this.StorePath);
                }
            }

            foreach (CertificateIdentifier trustedCertificate in TrustedCertificates)
            {
                X509Certificate2 certificate = await trustedCertificate.Find();

                if (certificate != null)
                {
                    collection.Add(certificate);
                }
            }

            return collection;
        }
        internal static X509Certificate2Collection GetRemoteCertificatesFromStoreContext(SafeFreeCertContext certContext)
        {
            X509Certificate2Collection result = new X509Certificate2Collection();

            if (certContext.IsInvalid)
            {
                return result;
            }

            Interop.Crypt32.CERT_CONTEXT context =
                Marshal.PtrToStructure<Interop.Crypt32.CERT_CONTEXT>(certContext.DangerousGetHandle());

            if (context.hCertStore != IntPtr.Zero)
            {
                Interop.Crypt32.CERT_CONTEXT* last = null;

                while (true)
                {
                    Interop.Crypt32.CERT_CONTEXT* next =
                        Interop.Crypt32.CertEnumCertificatesInStore(context.hCertStore, last);

                    if (next == null)
                    {
                        break;
                    }

                    var cert = new X509Certificate2(new IntPtr(next));
                    if (GlobalLog.IsEnabled)
                    {
                        GlobalLog.Print(
                            "UnmanagedCertificateContext::GetRemoteCertificatesFromStoreContext " +
                            "adding remote certificate:" + cert.Subject + cert.Thumbprint);
                    }

                    result.Add(cert);
                    last = next;
                }
            }

            return result;
        }
		internal static void CheckRemoteCertificate (TlsConfiguration config, MX.X509CertificateCollection certificates)
		{
			if (certificates == null || certificates.Count < 1)
				throw new TlsException (AlertDescription.CertificateUnknown);

			var helper = CertificateValidationHelper.GetValidator (config.TlsSettings);

			X509Certificate2Collection scerts = null;
			if (certificates != null) {
				scerts = new X509Certificate2Collection ();
				for (int i = 0; i < certificates.Count; i++)
					scerts.Add (new X509Certificate2 (certificates [i].RawData));
			}

			var result = helper.ValidateChain (config.TargetHost, scerts);
			if (result != null && result.Trusted && !result.UserDenied)
				return;

			// FIXME: check other values to report correct error type.
			throw new TlsException (AlertDescription.CertificateUnknown);
		}
Example #22
0
            public void CloneTo(X509Certificate2Collection collection)
            {
                EnumCertificatesContext context = default;

                context.Results = new HashSet <X509Certificate2>();
                unsafe
                {
                    bool success = Interop.AndroidCrypto.X509StoreEnumerateCertificates(
                        _keyStoreHandle,
                        &EnumCertificatesCallback,
                        Unsafe.AsPointer(ref context));
                    if (!success)
                    {
                        throw new CryptographicException(SR.Cryptography_X509_StoreEnumerateFailure);
                    }
                }

                foreach (X509Certificate2 cert in context.Results)
                {
                    collection.Add(cert);
                }
            }
		internal static void CheckClientCertificate (TlsContext context, MX.X509CertificateCollection certificates)
		{
			if (context.SettingsProvider.HasClientCertificateParameters) {
				var certParams = context.SettingsProvider.ClientCertificateParameters;
				if (certParams.CertificateAuthorities.Count > 0) {
					if (!certParams.CertificateAuthorities.Contains (certificates [0].IssuerName))
						throw new TlsException (AlertDescription.BadCertificate);
				}
			}

			var helper = CertificateValidationHelper.GetValidator (context.Configuration.TlsSettings);

			X509Certificate2Collection scerts = null;
			if (certificates != null) {
				scerts = new X509Certificate2Collection ();
				for (int i = 0; i < certificates.Count; i++)
					scerts.Add (new X509Certificate2 (certificates [i].RawData));
			}

			var result = helper.ValidateClientCertificate (scerts);
			if (result == null || !result.Trusted || result.UserDenied)
				throw new TlsException (AlertDescription.CertificateUnknown);
		}
        internal static X509Certificate2Collection GetRemoteCertificatesFromStoreContext(SafeFreeCertContext certContext)
        {
            X509Certificate2Collection result = new X509Certificate2Collection();

            if (certContext.IsInvalid)
            {
                return result;
            }

            Interop.Crypt32.CERT_CONTEXT context =
                Marshal.PtrToStructure<Interop.Crypt32.CERT_CONTEXT>(certContext.DangerousGetHandle());

            if (context.hCertStore != IntPtr.Zero)
            {
                Interop.Crypt32.CERT_CONTEXT* last = null;

                while (true)
                {
                    Interop.Crypt32.CERT_CONTEXT* next =
                        Interop.Crypt32.CertEnumCertificatesInStore(context.hCertStore, last);

                    if (next == null)
                    {
                        break;
                    }

                    var cert = new X509Certificate2(new IntPtr(next));
                    if (NetEventSource.IsEnabled) NetEventSource.Info(certContext, $"Adding remote certificate:{cert}");

                    result.Add(cert);
                    last = next;
                }
            }

            return result;
        }
Example #25
0
        private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestHandle, Uri requestUri)
        {
            // Must be HTTPS scheme to use client certificates.
            if (requestUri.Scheme != UriSchemeHttps)
            {
                return;
            }

            // Get candidate list for client certificates.
            X509Certificate2Collection certs;
            if (_clientCertificateOption == ClientCertificateOption.Manual)
            {
                certs = ClientCertificates;
            }
            else
            {
                using (var myStore = new X509Store())
                {
                    myStore.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
                    certs = myStore.Certificates;
                }
            }

            // Check for no certs now as a performance optimization.
            if (certs.Count == 0)
            {
                SetNoClientCertificate(requestHandle);
                return;
            }

            // Reduce the set of certificates to match the proper 'Client Authentication' criteria.
            certs = certs.Find(X509FindType.FindByKeyUsage, X509KeyUsageFlags.DigitalSignature, true);
            certs = certs.Find(X509FindType.FindByApplicationPolicy, ClientAuthenticationOID, true);

            // Build a new collection with certs that have a private key. Need to do this
            // manually because there is no X509FindType to match this criteria.
            var clientCerts = new X509Certificate2Collection();
            foreach (var cert in certs)
            {
                if (cert.HasPrivateKey)
                {
                    clientCerts.Add(cert);
                }
            }

            // TOOD: Filter the list based on TrustedIssuerList info from WINHTTP.

            // Set the client certificate.
            if (certs.Count == 0)
            {
                SetNoClientCertificate(requestHandle);
            }
            else
            {
                SetWinHttpOption(
                    requestHandle,
                    Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
                    clientCerts[0].Handle,
                    (uint)Marshal.SizeOf<Interop.Crypt32.CERT_CONTEXT>());
            }
        }
Example #26
0
        static string SendAPNS(string deviceToken, string content)
        {
            //ref:https://msdn.microsoft.com/en-us/library/txafckwd.aspx
            //ref2:http://stackoverflow.com/questions/16101100/string-format-input-string-was-not-in-correct-format-for-string-with-curly-brack
            //要多加雙括號"{{"才能讓參數寫入string的format
            string jsonContent = String.Format("{{\"aps:\":{{\"alert\":\"{0}\",\"badge\":8,\"sound\":\"default\"}}}}", deviceToken);
            //Json: { MID = 1000242, MsgID = 12345, RegID = "c1564dd73cd73a003d2ad143d96c9e6d651f8b48b45ba8c0ae9c5db87513fde8", Subj = "測試12 主題一:88個badge", Sum = 88, Title = "test2 Content" };
            //str = "{\"aps\":{\"alert\":\"" + s2 + "\",\"badge\":10,\"sound\":\"default\"}}";
            //string hostIP = "gateway.sandbox.push.apple.com";//"gateway.push.apple.com";//;//feedback.sandbox.push.apple.com//"feedback.sandbox.push.apple.com";
            int    port     = 2195;     //2196;
            string password = "******"; //AllPay

            //certificate load 需要去Apple申請App的憑證才有此檔
            string certificatepath     = "aps_production_allpay.p12";//"allpay_apns_dev.p12" ;//"AllPayEPAPNS.p12"//企業版prod;// //"allpay.p12";//bin/debug
            string certificateFullPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppleCertificate", certificatepath);

            certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(File.ReadAllBytes(certificateFullPath), password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            var certificates = new System.Security.Cryptography.X509Certificates.X509Certificate2Collection();

            certificates.Add(certificate);

            //使用TCP Cient來建立connect(就是走簡易的http)
            TcpClient apnsClient = new TcpClient();
            Stopwatch timer      = new Stopwatch();

            try
            {
                timer.Start();
                apnsClient.Connect(hostIP, port);
            }
            catch (SocketException ex)
            {
                timer.Stop();
                Console.WriteLine("TimeSpend:{0}ms  ex:{1}", timer.ElapsedMilliseconds, ex.Message);
            }
            //主要認證憑證就是這段,可以使用event認證兩方的憑證,目前APNs這邊都只使用Apple給的憑證
            System.Net.Security.SslStream apnsStream = new System.Net.Security.SslStream(apnsClient.GetStream(),
                                                                                         false,
                                                                                         new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate),
                                                                                         new System.Net.Security.LocalCertificateSelectionCallback(SelectLocalCertificate));

            try
            {
                apnsStream.AuthenticateAsClient(hostIP, certificates, System.Security.Authentication.SslProtocols.Tls, false);
                timer.Stop();
                Console.WriteLine("做完認證的TimeSpend:{0}ms", timer.ElapsedMilliseconds);
            }
            catch (System.Security.Authentication.AuthenticationException ex)
            {
                Console.WriteLine("error:" + ex.Message);
            }


            if (!apnsStream.IsMutuallyAuthenticated)
            {
                Console.WriteLine("error:" + "Ssl Stream Failed to Authenticate");
            }

            if (!apnsStream.CanWrite)
            {
                Console.WriteLine("error:" + "Ssl Stream is not Writable");
                return("");
            }
            //需要取得Apple手機給的token來當作裝置的識別碼,送的格式參考APPLE規定的JSON
            byte[] message = ToBytes(deviceToken, content);
            apnsStream.Write(message);//這邊就可以開始送資料了
            apnsStream.Close();
            return(Encoding.UTF8.GetString(message));
        }
        public static IChainPal BuildChain(
            X509Certificate2 leaf,
            X509Certificate2Collection candidates,
            OidCollection applicationPolicy,
            OidCollection certificatePolicy,
            DateTime verificationTime)
        {
            X509ChainElement[] elements;
            List<X509ChainStatus> overallStatus = new List<X509ChainStatus>();

            // An X509_STORE is more comparable to Cryptography.X509Certificate2Collection than to
            // Cryptography.X509Store. So read this with OpenSSL eyes, not CAPI/CNG eyes.
            //
            // (If you need to think of it as an X509Store, it's a volatile memory store)
            using (SafeX509StoreHandle store = Interop.libcrypto.X509_STORE_new())
            using (SafeX509StoreCtxHandle storeCtx = Interop.libcrypto.X509_STORE_CTX_new())
            {
                Interop.libcrypto.CheckValidOpenSslHandle(store);
                Interop.libcrypto.CheckValidOpenSslHandle(storeCtx);

                foreach (X509Certificate2 cert in candidates)
                {
                    OpenSslX509CertificateReader pal = (OpenSslX509CertificateReader)cert.Pal;

                    if (!Interop.libcrypto.X509_STORE_add_cert(store, pal.SafeHandle))
                    {
                        throw Interop.libcrypto.CreateOpenSslCryptographicException();
                    }
                }

                // When CRL checking support is added, it should be done before the call to
                // X509_STORE_CTX_init (aka here) by calling X509_STORE_set_flags(store, flags);

                SafeX509Handle leafHandle = ((OpenSslX509CertificateReader)leaf.Pal).SafeHandle;

                if (!Interop.libcrypto.X509_STORE_CTX_init(storeCtx, store, leafHandle, IntPtr.Zero))
                {
                    throw Interop.libcrypto.CreateOpenSslCryptographicException();
                }

                Interop.Crypto.SetX509ChainVerifyTime(storeCtx, verificationTime);

                int verify = Interop.libcrypto.X509_verify_cert(storeCtx);

                if (verify < 0)
                {
                    throw Interop.libcrypto.CreateOpenSslCryptographicException();
                }

                using (SafeX509StackHandle chainStack = Interop.libcrypto.X509_STORE_CTX_get1_chain(storeCtx))
                {
                    int chainSize = Interop.Crypto.GetX509StackFieldCount(chainStack);
                    int errorDepth = -1;
                    Interop.libcrypto.X509VerifyStatusCode errorCode = 0;
                    string errorMsg = null;

                    if (verify == 0)
                    {
                        errorCode = Interop.libcrypto.X509_STORE_CTX_get_error(storeCtx);
                        errorDepth = Interop.libcrypto.X509_STORE_CTX_get_error_depth(storeCtx);
                        errorMsg = Interop.libcrypto.X509_verify_cert_error_string(errorCode);
                    }

                    elements = new X509ChainElement[chainSize];

                    for (int i = 0; i < chainSize; i++)
                    {
                        List<X509ChainStatus> status = new List<X509ChainStatus>();

                        if (i == errorDepth)
                        {
                            X509ChainStatus chainStatus = new X509ChainStatus
                            {
                                Status = MapVerifyErrorToChainStatus(errorCode),
                                StatusInformation = errorMsg,
                            };

                            status.Add(chainStatus);
                            AddUniqueStatus(overallStatus, ref chainStatus);
                        }

                        IntPtr elementCertPtr = Interop.Crypto.GetX509StackField(chainStack, i);

                        if (elementCertPtr == IntPtr.Zero)
                        {
                            throw Interop.libcrypto.CreateOpenSslCryptographicException();
                        }

                        // Duplicate the certificate handle
                        X509Certificate2 elementCert = new X509Certificate2(elementCertPtr);

                        elements[i] = new X509ChainElement(elementCert, status.ToArray(), "");
                    }
                }
            }

            if ((certificatePolicy != null && certificatePolicy.Count > 0) ||
                (applicationPolicy != null && applicationPolicy.Count > 0))
            {
                X509Certificate2Collection certsToRead = new X509Certificate2Collection();

                foreach (X509ChainElement element in elements)
                {
                    certsToRead.Add(element.Certificate);
                }

                CertificatePolicyChain policyChain = new CertificatePolicyChain(certsToRead);

                bool failsPolicyChecks = false;

                if (certificatePolicy != null)
                {
                    if (!policyChain.MatchesCertificatePolicies(certificatePolicy))
                    {
                        failsPolicyChecks = true;
                    }
                }

                if (applicationPolicy != null)
                {
                    if (!policyChain.MatchesApplicationPolicies(applicationPolicy))
                    {
                        failsPolicyChecks = true;
                    }
                }

                if (failsPolicyChecks)
                {
                    X509ChainElement leafElement = elements[0];

                    X509ChainStatus chainStatus = new X509ChainStatus
                    {
                        Status = X509ChainStatusFlags.InvalidPolicyConstraints,
                        StatusInformation = SR.Chain_NoPolicyMatch,
                    };

                    var elementStatus = new List<X509ChainStatus>(leafElement.ChainElementStatus.Length + 1);
                    elementStatus.AddRange(leafElement.ChainElementStatus);

                    AddUniqueStatus(elementStatus, ref chainStatus);
                    AddUniqueStatus(overallStatus, ref chainStatus);

                    elements[0] = new X509ChainElement(
                        leafElement.Certificate,
                        elementStatus.ToArray(),
                        leafElement.Information);
                }
            }

            return new OpenSslX509ChainProcessor
            {
                ChainStatus = overallStatus.ToArray(),
                ChainElements = elements,
            };
        }
        internal static X509Certificate2Collection FindCandidates(
            X509Certificate2 leaf,
            X509Certificate2Collection extraStore)
        {
            X509Certificate2Collection candidates = new X509Certificate2Collection();
            Queue<X509Certificate2> toProcess = new Queue<X509Certificate2>();
            toProcess.Enqueue(leaf);

            using (var rootStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine))
            using (var intermediateStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine))
            {
                rootStore.Open(OpenFlags.ReadOnly);
                intermediateStore.Open(OpenFlags.ReadOnly);

                X509Certificate2Collection rootCerts = rootStore.Certificates;
                X509Certificate2Collection intermediateCerts = intermediateStore.Certificates;

                X509Certificate2Collection[] storesToCheck =
                {
                    extraStore,
                    intermediateCerts,
                    rootCerts,
                };

                while (toProcess.Count > 0)
                {
                    X509Certificate2 current = toProcess.Dequeue();

                    if (!candidates.Contains(current))
                    {
                        candidates.Add(current);
                    }

                    X509Certificate2Collection results = FindIssuer(
                        current,
                        storesToCheck);

                    if (results != null)
                    {
                        foreach (X509Certificate2 result in results)
                        {
                            if (!candidates.Contains(result))
                            {
                                toProcess.Enqueue(result);
                            }
                        }
                    }
                }
            }

            return candidates;
        }
Example #29
0
 public static X509Certificate2Collection GetOriginatorCerts(this SafeCryptMsgHandle hCryptMsg)
 {
     int numCertificates = 0;
     int cbNumCertificates = sizeof(int);
     if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, CryptMsgParamType.CMSG_CERT_COUNT_PARAM, 0, out numCertificates, ref cbNumCertificates))
         throw Marshal.GetLastWin32Error().ToCryptographicException();
     X509Certificate2Collection certs = new X509Certificate2Collection();
     for (int index = 0; index < numCertificates; index++)
     {
         byte[] encodedCertificate = hCryptMsg.GetMsgParamAsByteArray(CryptMsgParamType.CMSG_CERT_PARAM, index);
         X509Certificate2 cert = new X509Certificate2(encodedCertificate);
         certs.Add(cert);
     }
     return certs;
 }
        /// <summary cref="ICertificateStore.FindByThumbprint(string)" />
        public async Task<X509Certificate2Collection> FindByThumbprint(string thumbprint)
        {
            X509Certificate2Collection certificates = new X509Certificate2Collection();

            // find existing certificate.
            IBuffer pCertContext = await FindCertificate(thumbprint);
            if (pCertContext == null)
            {
                return certificates;
            }

            // create the certificate.
            byte[] certContext = new byte[pCertContext.Length];
            CryptographicBuffer.CopyToByteArray(pCertContext, out certContext);
            certificates.Add(new X509Certificate2(certContext));
            return certificates;
        }
        /// <summary cref="ICertificateStore.Enumerate()" />
        public async Task<X509Certificate2Collection> Enumerate()
        {
            X509Certificate2Collection certificates = new X509Certificate2Collection();

            // get the certificates.
            IReadOnlyList<Certificate> list = await CertificateStores.FindAllAsync();

            for (int ii = 0; ii < list.Count; ii++)
            {
                // add the certificate.
                IBuffer buffer = list[ii].GetCertificateBlob();
                byte[] cert = new byte[buffer.Length];
                CryptographicBuffer.CopyToByteArray(buffer, out cert);

                X509Certificate2 certificate = new X509Certificate2(cert);
                certificates.Add(certificate);
            }

            return certificates;
        }
        /// <summary cref="ICertificateStore.Enumerate()" />
        public X509Certificate2Collection Enumerate()
        {
            lock (m_lock)
            {   
	            X509Certificate2Collection certificates = new X509Certificate2Collection();

	            IntPtr hStore = IntPtr.Zero;
	            X509Store store = null;

	            // find the certificate.
	            try
	            {
                    // open store.
                    hStore = OpenStore(true, false, false);

		            if (hStore == IntPtr.Zero)
		            {
                        return certificates;
		            }

		            // wrap it with a managed store.
                    store = new X509Store(hStore);
                    
		            // get the certificates.
		            for (int ii = 0; ii < store.Certificates.Count; ii++)
		            {
			            certificates.Add(store.Certificates[ii]);
		            }
	            }
	            finally
	            {
		            if (store != null)
		            {
			            store.Close();
		            }

		            if (hStore != IntPtr.Zero)
                    {
                        int result = NativeMethods.CertCloseStore(hStore, 0);

                        if (result == 0)
                        {
                            Utils.Trace("Could not close certificate store. Error={0:X8}", Marshal.GetLastWin32Error());
                        }
		            }
	            }

	            return certificates;
            }
        }
Example #33
0
        void ResolveIssuers(X509Certificate2 certificate, X509Certificate2Collection issuers, int chainLength)
        {
            //
            // only look at simpleNames because intermediates are always going to be org-level, not email, certs
            //
            string issuerName = certificate.GetNameInfo(X509NameType.SimpleName, true); // true == "for issuer"
            //
            // If the issuer name matches the Cert name, we have a self-signed cert
            //
            if (certificate.MatchName(issuerName))
            {
                return;
            }
            //
            // If the issuer is already known, then we are good
            //
            if (issuers.FindByName(issuerName) != null)
            {
                return;
            }

            if (chainLength == m_maxIssuerChainLength)
            {
                //
                // Chain too long. Ignore...
                //
                return;
            }
            //
            // Retrieve the issuer's certificate
            //
            X509Certificate2Collection issuerCertificates = m_certResolver.SafeGetCertificates(certificate.ExtractEmailNameOrName(true));
            if (CollectionExtensions.IsNullOrEmpty(issuerCertificates))
            {
                return;
            }
            //
            // Recursively fetch the issuers who issued this set of certificates
            //
            foreach (X509Certificate2 issuerCertificate in issuerCertificates)
            {
                if (issuerCertificate.MatchName(issuerName) && !issuers.ContainsThumbprint(issuerCertificate.Thumbprint))
                {
                    //
                    // New issuer
                    //
                    issuers.Add(issuerCertificate);
                    //
                    // And keep working up the chain
                    //
                    this.ResolveIssuers(issuerCertificate, issuers, chainLength + 1);
                }
            }
        }
        public X509Certificate2Collection Find(X509FindType findType, object findValue, bool validOnly)
        {
            if (findValue == null)
            {
                throw new ArgumentNullException("findValue");
            }
            string            text              = string.Empty;
            string            text2             = string.Empty;
            X509KeyUsageFlags x509KeyUsageFlags = X509KeyUsageFlags.None;
            DateTime          t = DateTime.MinValue;

            switch (findType)
            {
            case X509FindType.FindByThumbprint:
            case X509FindType.FindBySubjectName:
            case X509FindType.FindBySubjectDistinguishedName:
            case X509FindType.FindByIssuerName:
            case X509FindType.FindByIssuerDistinguishedName:
            case X509FindType.FindBySerialNumber:
            case X509FindType.FindByTemplateName:
            case X509FindType.FindBySubjectKeyIdentifier:
                try
                {
                    text = (string)findValue;
                }
                catch (Exception inner)
                {
                    string text3 = Locale.GetText("Invalid find value type '{0}', expected '{1}'.", new object[]
                    {
                        findValue.GetType(),
                        "string"
                    });
                    throw new CryptographicException(text3, inner);
                }
                break;

            case X509FindType.FindByTimeValid:
            case X509FindType.FindByTimeNotYetValid:
            case X509FindType.FindByTimeExpired:
                try
                {
                    t = (DateTime)findValue;
                }
                catch (Exception inner2)
                {
                    string text4 = Locale.GetText("Invalid find value type '{0}', expected '{1}'.", new object[]
                    {
                        findValue.GetType(),
                        "X509DateTime"
                    });
                    throw new CryptographicException(text4, inner2);
                }
                break;

            case X509FindType.FindByApplicationPolicy:
            case X509FindType.FindByCertificatePolicy:
            case X509FindType.FindByExtension:
                try
                {
                    text2 = (string)findValue;
                }
                catch (Exception inner3)
                {
                    string text5 = Locale.GetText("Invalid find value type '{0}', expected '{1}'.", new object[]
                    {
                        findValue.GetType(),
                        "X509KeyUsageFlags"
                    });
                    throw new CryptographicException(text5, inner3);
                }
                try
                {
                    CryptoConfig.EncodeOID(text2);
                }
                catch (CryptographicUnexpectedOperationException)
                {
                    string text6 = Locale.GetText("Invalid OID value '{0}'.", new object[]
                    {
                        text2
                    });
                    throw new ArgumentException("findValue", text6);
                }
                break;

            case X509FindType.FindByKeyUsage:
                try
                {
                    x509KeyUsageFlags = (X509KeyUsageFlags)((int)findValue);
                }
                catch (Exception inner4)
                {
                    string text7 = Locale.GetText("Invalid find value type '{0}', expected '{1}'.", new object[]
                    {
                        findValue.GetType(),
                        "X509KeyUsageFlags"
                    });
                    throw new CryptographicException(text7, inner4);
                }
                break;

            default:
            {
                string text8 = Locale.GetText("Invalid find type '{0}'.", new object[]
                    {
                        findType
                    });
                throw new CryptographicException(text8);
            }
            }
            CultureInfo invariantCulture = CultureInfo.InvariantCulture;
            X509Certificate2Collection x509Certificate2Collection = new X509Certificate2Collection();

            foreach (object obj in base.InnerList)
            {
                X509Certificate2 x509Certificate = (X509Certificate2)obj;
                bool             flag            = false;
                switch (findType)
                {
                case X509FindType.FindByThumbprint:
                    flag = (string.Compare(text, x509Certificate.Thumbprint, true, invariantCulture) == 0 || string.Compare(text, x509Certificate.GetCertHashString(), true, invariantCulture) == 0);
                    break;

                case X509FindType.FindBySubjectName:
                {
                    string nameInfo = x509Certificate.GetNameInfo(X509NameType.SimpleName, false);
                    flag = (nameInfo.IndexOf(text, StringComparison.InvariantCultureIgnoreCase) >= 0);
                    break;
                }

                case X509FindType.FindBySubjectDistinguishedName:
                    flag = (string.Compare(text, x509Certificate.Subject, true, invariantCulture) == 0);
                    break;

                case X509FindType.FindByIssuerName:
                {
                    string nameInfo2 = x509Certificate.GetNameInfo(X509NameType.SimpleName, true);
                    flag = (nameInfo2.IndexOf(text, StringComparison.InvariantCultureIgnoreCase) >= 0);
                    break;
                }

                case X509FindType.FindByIssuerDistinguishedName:
                    flag = (string.Compare(text, x509Certificate.Issuer, true, invariantCulture) == 0);
                    break;

                case X509FindType.FindBySerialNumber:
                    flag = (string.Compare(text, x509Certificate.SerialNumber, true, invariantCulture) == 0);
                    break;

                case X509FindType.FindByTimeValid:
                    flag = (t >= x509Certificate.NotBefore && t <= x509Certificate.NotAfter);
                    break;

                case X509FindType.FindByTimeNotYetValid:
                    flag = (t < x509Certificate.NotBefore);
                    break;

                case X509FindType.FindByTimeExpired:
                    flag = (t > x509Certificate.NotAfter);
                    break;

                case X509FindType.FindByApplicationPolicy:
                    flag = (x509Certificate.Extensions.Count == 0);
                    break;

                case X509FindType.FindByExtension:
                    flag = (x509Certificate.Extensions[text2] != null);
                    break;

                case X509FindType.FindByKeyUsage:
                {
                    X509KeyUsageExtension x509KeyUsageExtension = x509Certificate.Extensions["2.5.29.15"] as X509KeyUsageExtension;
                    flag = (x509KeyUsageExtension == null || (x509KeyUsageExtension.KeyUsages & x509KeyUsageFlags) == x509KeyUsageFlags);
                    break;
                }

                case X509FindType.FindBySubjectKeyIdentifier:
                {
                    X509SubjectKeyIdentifierExtension x509SubjectKeyIdentifierExtension = x509Certificate.Extensions["2.5.29.14"] as X509SubjectKeyIdentifierExtension;
                    if (x509SubjectKeyIdentifierExtension != null)
                    {
                        flag = (string.Compare(text, x509SubjectKeyIdentifierExtension.SubjectKeyIdentifier, true, invariantCulture) == 0);
                    }
                    break;
                }
                }
                if (flag)
                {
                    if (validOnly)
                    {
                        try
                        {
                            if (x509Certificate.Verify())
                            {
                                x509Certificate2Collection.Add(x509Certificate);
                            }
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
                        x509Certificate2Collection.Add(x509Certificate);
                    }
                }
            }
            return(x509Certificate2Collection);
        }
        public X509Certificate2Collection Find(X509FindType findType, object findValue, bool validOnly)
        {
            if (findValue == null)
            {
                throw new ArgumentNullException("findValue");
            }

            string            str = String.Empty;
            string            oid = String.Empty;
            X509KeyUsageFlags ku  = X509KeyUsageFlags.None;
            DateTime          dt  = DateTime.MinValue;

            switch (findType)
            {
            case X509FindType.FindByThumbprint:
            case X509FindType.FindBySubjectName:
            case X509FindType.FindBySubjectDistinguishedName:
            case X509FindType.FindByIssuerName:
            case X509FindType.FindByIssuerDistinguishedName:
            case X509FindType.FindBySerialNumber:
            case X509FindType.FindByTemplateName:
            case X509FindType.FindBySubjectKeyIdentifier:
                try {
                    str = (string)findValue;
                }
                catch (Exception e) {
                    string msg = Locale.GetText("Invalid find value type '{0}', expected '{1}'.",
                                                findValue.GetType(), "string");
                    throw new CryptographicException(msg, e);
                }
                break;

            case X509FindType.FindByApplicationPolicy:
            case X509FindType.FindByCertificatePolicy:
            case X509FindType.FindByExtension:
                try {
                    oid = (string)findValue;
                }
                catch (Exception e) {
                    string msg = Locale.GetText("Invalid find value type '{0}', expected '{1}'.",
                                                findValue.GetType(), "X509KeyUsageFlags");
                    throw new CryptographicException(msg, e);
                }
                // OID validation
                try {
                    CryptoConfig.EncodeOID(oid);
                }
                catch (CryptographicUnexpectedOperationException) {
                    string msg = Locale.GetText("Invalid OID value '{0}'.", oid);
                    throw new ArgumentException("findValue", msg);
                }
                break;

            case X509FindType.FindByKeyUsage:
                try {
                    ku = (X509KeyUsageFlags)findValue;
                }
                catch (Exception e) {
                    string msg = Locale.GetText("Invalid find value type '{0}', expected '{1}'.",
                                                findValue.GetType(), "X509KeyUsageFlags");
                    throw new CryptographicException(msg, e);
                }
                break;

            case X509FindType.FindByTimeValid:
            case X509FindType.FindByTimeNotYetValid:
            case X509FindType.FindByTimeExpired:
                try {
                    dt = (DateTime)findValue;
                }
                catch (Exception e) {
                    string msg = Locale.GetText("Invalid find value type '{0}', expected '{1}'.",
                                                findValue.GetType(), "X509DateTime");
                    throw new CryptographicException(msg, e);
                }
                break;

            default:
            {
                string msg = Locale.GetText("Invalid find type '{0}'.", findType);
                throw new CryptographicException(msg);
            }
            }

            CultureInfo cinv = CultureInfo.InvariantCulture;
            X509Certificate2Collection results = new  X509Certificate2Collection();

            foreach (X509Certificate2 x in InnerList)
            {
                bool value_match = false;

                switch (findType)
                {
                case X509FindType.FindByThumbprint:
                    // works with Thumbprint, GetCertHashString in both normal (upper) and lower case
                    value_match = ((String.Compare(str, x.Thumbprint, true, cinv) == 0) ||
                                   (String.Compare(str, x.GetCertHashString(), true, cinv) == 0));
                    break;

                case X509FindType.FindBySubjectName:
                    string [] names = x.SubjectName.Format(true).Split(newline_split, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string name in names)
                    {
                        int pos = name.IndexOf('=');
                        value_match = (name.IndexOf(str, pos, StringComparison.InvariantCultureIgnoreCase) >= 0);
                        if (value_match)
                        {
                            break;
                        }
                    }
                    break;

                case X509FindType.FindBySubjectDistinguishedName:
                    value_match = (String.Compare(str, x.Subject, true, cinv) == 0);
                    break;

                case X509FindType.FindByIssuerName:
                    string iname = x.GetNameInfo(X509NameType.SimpleName, true);
                    value_match = (iname.IndexOf(str, StringComparison.InvariantCultureIgnoreCase) >= 0);
                    break;

                case X509FindType.FindByIssuerDistinguishedName:
                    value_match = (String.Compare(str, x.Issuer, true, cinv) == 0);
                    break;

                case X509FindType.FindBySerialNumber:
                    value_match = (String.Compare(str, x.SerialNumber, true, cinv) == 0);
                    break;

                case X509FindType.FindByTemplateName:
                    // TODO - find a valid test case
                    break;

                case X509FindType.FindBySubjectKeyIdentifier:
                    value_match = (String.Compare(str, GetKeyIdentifier(x), true, cinv) == 0);
                    break;

                case X509FindType.FindByApplicationPolicy:
                    // note: include when no extensions are present (even if v3)
                    value_match = (x.Extensions.Count == 0);
                    // TODO - find test case with extension
                    break;

                case X509FindType.FindByCertificatePolicy:
                    // TODO - find test case with extension
                    break;

                case X509FindType.FindByExtension:
                    value_match = (x.Extensions [oid] != null);
                    break;

                case X509FindType.FindByKeyUsage:
                    X509KeyUsageExtension kue = (x.Extensions ["2.5.29.15"] as X509KeyUsageExtension);
                    if (kue == null)
                    {
                        // key doesn't have any hard coded limitations
                        // note: MS doesn't check for ExtendedKeyUsage
                        value_match = true;
                    }
                    else
                    {
                        value_match = ((kue.KeyUsages & ku) == ku);
                    }
                    break;

                case X509FindType.FindByTimeValid:
                    value_match = ((dt >= x.NotBefore) && (dt <= x.NotAfter));
                    break;

                case X509FindType.FindByTimeNotYetValid:
                    value_match = (dt < x.NotBefore);
                    break;

                case X509FindType.FindByTimeExpired:
                    value_match = (dt > x.NotAfter);
                    break;
                }

                if (!value_match)
                {
                    continue;
                }

                if (validOnly)
                {
                    try {
                        if (x.Verify())
                        {
                            results.Add(x);
                        }
                    }
                    catch {
                    }
                }
                else
                {
                    results.Add(x);
                }
            }
            return(results);
        }