Exemplo n.º 1
0
        private async Task <Certificate> GetClientCertificate()
        {
            //await InstallCertificate(@"Assets\BigsbyRootCert.pfx", "RootCert");
            await InstallCertificate(@"Assets\BigsbyClientCert.pfx", "ClientCert");

            var names    = new List <string>();
            var certList = await CertificateStores.FindAllAsync();

            var certs = certList.ToList();

            var query = new CertificateQuery
            {
                FriendlyName = "ClientCert",
            };

            var queried = (await CertificateStores.FindAllAsync(query)).ToList();

            Certificate clientCert = null;

            // Always choose first enumerated certificate.  Works so long as there is only one cert
            // installed and it's the right one.
            if ((null != certList) && (certList.Count > 0))
            {
                clientCert = certList.First();
            }

            return(queried.First());
        }
Exemplo n.º 2
0
        async Task <Certificate> GetCertificate(MailboxAddress mailbox, bool sign)
        {
            var secure = mailbox as SecureMailboxAddress;
            var query  = new CertificateQuery();
            var now    = DateTimeOffset.UtcNow;

            if (secure != null)
            {
                query.Thumbprint = HexDecode(secure.Fingerprint);
            }
            else
            {
                query.FriendlyName = mailbox.Address;
            }

            // TODO: filter on key usages

            foreach (var certificate in await CertificateStores.FindAllAsync(query))
            {
                if (certificate.ValidFrom > now || certificate.ValidTo < now)
                {
                    continue;
                }

                return(certificate);
            }

            return(null);
        }
        private IReadOnlyList<Certificate> GetCertificatesFromWinRTStore(X509Certificate2 dotNetCertificate)
        {
            var query = new CertificateQuery
            {
                Thumbprint = dotNetCertificate.GetCertHash(),
                IncludeDuplicates = false
            };

            return CertificateStores.FindAllAsync(query).AsTask().GetAwaiter().GetResult();
        }
Exemplo n.º 4
0
        private IReadOnlyList <Certificate> GetCertificatesFromWinRTStore(X509Certificate2 dotNetCertificate)
        {
            var query = new CertificateQuery
            {
                Thumbprint        = dotNetCertificate.GetCertHash(),
                IncludeDuplicates = false
            };

            return(CertificateStores.FindAllAsync(query).AsTask().GetAwaiter().GetResult());
        }
Exemplo n.º 5
0
        private async void DoGet(bool ignoreCertErrors, string key, string value, string friendlyName)
        {
            ResponseHeadersBlock.Text = String.Empty;
            CertErrorsBlock.Text      = String.Empty;
            ResponseContentBlock.Text = String.Empty;

            HttpRequestMessage request = null;

            try
            {
                request = new HttpRequestMessage(
                    HttpMethod.Get,
                    new Uri(UriBox2.Text));

                HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();

                if (ignoreCertErrors)
                {
                    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
                    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
                    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.RevocationFailure);
                }

                if (!String.IsNullOrEmpty(friendlyName))
                {
                    CertificateQuery query = new CertificateQuery();
                    query.FriendlyName = friendlyName;
                    IReadOnlyCollection <Certificate> certs = await CertificateStores.FindAllAsync(query);

                    filter.ClientCertificate = certs.ElementAt(0);
                }

                HttpClient client = new HttpClient(filter);

                if (!String.IsNullOrEmpty(key))
                {
                    client.DefaultRequestHeaders.Add(key, value);
                }

                HttpResponseMessage response = await client.SendRequestAsync(request);

                ResponseHeadersBlock.Text = response.ReasonPhrase;
                ResponseContentBlock.Text = await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                ResponseHeadersBlock.Text = ex.ToString();

                // Something like: 'Untrusted, InvalidName, RevocationFailure'
                CertErrorsBlock.Text = String.Join(
                    ", ",
                    request.TransportInformation.ServerCertificateErrors);
            }
        }
Exemplo n.º 6
0
        private static void ValidateClientCertificate(X509Certificate2 certificate)
        {
#if FEATURE_NETNATIVE
            var query = new CertificateQuery
            {
                Thumbprint        = certificate.GetCertHash(),
                IncludeDuplicates = false,
                StoreName         = "MY"
            };

            if (CertificateStores.FindAllAsync(query).AsTask().GetAwaiter().GetResult().Count == 0)
            {
                throw ExceptionHelper.PlatformNotSupported("Certificate could not be found in the MY store.");
            }
            ;
#endif // FEATURE_NETNATIVE
        }
Exemplo n.º 7
0
        private async Task <Certificate> FindCertificate(IDictionary <string, string> challengeData)
        {
            CertificateQuery            query        = new CertificateQuery();
            IReadOnlyList <Certificate> certificates = null;
            string errMessage = null;

            if (challengeData.ContainsKey("CertAuthorities"))
            {
                errMessage = "Cert Authorities:" + challengeData["CertAuthorities"];
                PlatformPlugin.Logger.Verbose(null, "Looking up certificate matching authorities:" + challengeData["CertAuthorities"]);
                string[] certAuthorities = challengeData["CertAuthorities"].Split(';');
                foreach (var certAuthority in certAuthorities)
                {
                    //reverse the tokenized string and replace "," with " + "
                    string[] dNames = certAuthority.Split(new[] { "," }, StringSplitOptions.None);
                    string   distinguishedIssuerName = dNames[dNames.Length - 1];
                    for (int i = dNames.Length - 2; i >= 0; i--)
                    {
                        distinguishedIssuerName += " + " + dNames[i].Trim();
                    }

                    query.IssuerName = distinguishedIssuerName;
                    certificates     = await CertificateStores.FindAllAsync(query);

                    if (certificates.Count > 0)
                    {
                        break;
                    }
                }
            }
            else
            {
                errMessage = "Cert Thumbprint:" + challengeData["CertThumbprint"];
                PlatformPlugin.Logger.Verbose(null, "Looking up certificate matching thumbprint:" + challengeData["CertThumbprint"]);
                query.Thumbprint = HexStringToByteArray(challengeData["CertThumbprint"]);
                certificates     = await CertificateStores.FindAllAsync(query);
            }

            if (certificates == null || certificates.Count == 0)
            {
                throw new AdalException(AdalError.DeviceCertificateNotFound,
                                        string.Format(AdalErrorMessage.DeviceCertificateNotFoundTemplate, errMessage));
            }

            return(certificates[0]);
        }
        private async Task <Certificate> FindCertificateFromStoreAsync()
        {
            // Find the client certificate for authentication. If not found, it means it has not been installed.
            CertificateQuery query = new CertificateQuery();

            query.IssuerName   = ClientCertIssuerName;
            query.FriendlyName = ClientCertFriendlyName;

            IReadOnlyList <Certificate> certs = await CertificateStores.FindAllAsync(query);

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

            // This sample installs only one certificate, so if we find one, it must be ours.
            return(certs[0]);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Returns a certificate with a given name
        /// </summary>
        /// <param name="certName">Name of cert we are going to look for</param>
        /// <returns>null if the cert isn't there, otherwise the cert that was found.</returns>
        public static async Task <Certificate> FindCert(string certName)
        {
            // Work around for the TplEventListener not working correctly.
            // https://social.msdn.microsoft.com/Forums/windowsapps/en-US/3e505e04-7f30-4313-aa47-275eaef333dd/systemargumentexception-use-of-undefined-keyword-value-1-for-event-taskscheduled-in-async?forum=wpdevelop
            await Task.Delay(1);

            // Do the CERT query

            var query = new CertificateQuery();

            query.FriendlyName = certName;
            var certificates = await CertificateStores.FindAllAsync(query);

            if (certificates.Count != 1)
            {
                return(null);
            }
            return(certificates[0]);
        }
Exemplo n.º 10
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                CertificateQuery q = new CertificateQuery();
                q.HardwareOnly = true;
                q.IssuerName   = "Citizen CA";
                IReadOnlyList <Certificate> certs = await CertificateStores.FindAllAsync(q);

                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.ViewMode = PickerViewMode.Thumbnail;
                openPicker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
                openPicker.FileTypeFilter.Add(".p12");
                openPicker.FileTypeFilter.Add(".acc-p12");

                StorageFile file = await openPicker.PickSingleFileAsync();
            } catch
            {
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Finds a certificate in the store.
        /// </summary>
        /// <param name="hStore">The handle for the store to search.</param>
        /// <param name="thumbprint">The thumbprint of the certificate to find.</param>
        /// <returns>The context for the matching certificate.</returns>
        private static async Task <IBuffer> FindCertificate(string thumbprint)
        {
            byte[] byteThumbprint = new byte[thumbprint.Length];
            for (int i = 0; i < thumbprint.Length; i++)
            {
                byteThumbprint[i] = (byte)thumbprint[i];
            }

            CertificateQuery query = new CertificateQuery();

            query.Thumbprint = byteThumbprint;
            IReadOnlyList <Certificate> list = await CertificateStores.FindAllAsync(query);

            if (list.Count > 0)
            {
                return(list[0].GetCertificateBlob());
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Gets the private key for the certificate matching the specified selector.
        /// </summary>
        /// <remarks>
        /// Gets the private key for the first certificate that matches the specified selector.
        /// </remarks>
        /// <returns>The private key on success; otherwise <c>null</c>.</returns>
        /// <param name="selector">The search criteria for the private key.</param>
        protected virtual async Task <AsymmetricKeyParameter> GetPrivateKeyAsync(IX509Selector selector)
        {
            // first we need to find the certificate...
            var match = selector as X509CertStoreSelector;
            var query = new CertificateQuery();

            if (match == null)
            {
                return(null);
            }

            if (match.Certificate != null)
            {
                query.Thumbprint = HexDecode(match.Certificate.GetFingerprint());
            }

            if (match.Issuer != null)
            {
                query.IssuerName = match.Issuer.ToString();
            }

            var certificates = await CertificateStores.FindAllAsync(query);

            var certificate = certificates.FirstOrDefault();

            if (certificate == null)
            {
                return(null);
            }

            // now get the key

            // TODO: what hash algo/padding do we want? does it matter?
            var key = await PersistedKeyProvider.OpenKeyPairFromCertificateAsync(certificate, HashAlgorithmNames.Sha256, CryptographicPadding.RsaPkcs1V15);

            var buffer = key.Export(CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey);

            return(LoadPrivateKey(buffer));
        }
Exemplo n.º 13
0
        /// <summary cref="ICertificateStore.Add(X509Certificate2)" />
        public async Task Add(X509Certificate2 certificate)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException("certificate");
            }

            // check for existing certificate.
            byte[] thumbprint = new byte[certificate.Thumbprint.Length];
            for (int i = 0; i < certificate.Thumbprint.Length; i++)
            {
                thumbprint[i] = (byte)certificate.Thumbprint[i];
            }

            CertificateQuery query = new CertificateQuery();

            query.Thumbprint = thumbprint;
            IReadOnlyList <Certificate> pCertContext = await CertificateStores.FindAllAsync(query);

            if (pCertContext.Count != 0)
            {
                throw ServiceResultException.Create(
                          StatusCodes.BadUnexpectedError,
                          "Certificate is already in the store.\r\nType={0}, Name={1}, Subject={2}",
                          m_storeType,
                          m_symbolicName,
                          certificate.Subject);
            }

            lock (m_lock)
            {
                // add certificate.
                CertificateFactory.AddCertificateToWindowsStore(
                    m_storeType == WindowsStoreType.LocalMachine,
                    m_symbolicName,
                    certificate);
            }
        }
Exemplo n.º 14
0
        /// <summary cref="ICertificateStore.Delete(string)" />
        public async Task <bool> Delete(string thumbprint)
        {
            // open store.
            CertificateStore hStore = OpenStore(false, false, false);

            if (hStore == null)
            {
                return(false);
            }

            // find certificate.
            byte[] byteThumbprint = new byte[thumbprint.Length];
            for (int i = 0; i < thumbprint.Length; i++)
            {
                byteThumbprint[i] = (byte)thumbprint[i];
            }

            CertificateQuery query = new CertificateQuery();

            query.Thumbprint = byteThumbprint;
            IReadOnlyList <Certificate> list = await CertificateStores.FindAllAsync(query);

            // delete certificate.
            if (list.Count > 0)
            {
                lock (m_lock)
                {
                    hStore.Delete(list[0]);
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 15
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                CertificateQuery q = new CertificateQuery();
                q.HardwareOnly = true;
                q.IssuerName = "Citizen CA";
                IReadOnlyList<Certificate> certs = await CertificateStores.FindAllAsync(q);

                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.ViewMode = PickerViewMode.Thumbnail;
                openPicker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
                openPicker.FileTypeFilter.Add(".p12");
                openPicker.FileTypeFilter.Add(".acc-p12");

                StorageFile file = await openPicker.PickSingleFileAsync();
            } catch
            { 

}
        }
        /// <summary cref="ICertificateStore.Delete(string)" />
        public async Task<bool> Delete(string thumbprint)
        {
            // open store.
            CertificateStore hStore = OpenStore(false, false, false);
            if (hStore == null)
            {
                return false;
            }

            // find certificate.
            byte[] byteThumbprint = new byte[thumbprint.Length];
            for (int i = 0; i < thumbprint.Length; i++)
            {
                byteThumbprint[i] = (byte)thumbprint[i];
            }

            CertificateQuery query = new CertificateQuery();
            query.Thumbprint = byteThumbprint;
            IReadOnlyList<Certificate> list = await CertificateStores.FindAllAsync(query);

            // delete certificate.
            if (list.Count > 0)
            {
                lock (m_lock)
                {
                    hStore.Delete(list[0]);
                }

                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// Finds a certificate in the store.
        /// </summary>
        /// <param name="hStore">The handle for the store to search.</param>
        /// <param name="thumbprint">The thumbprint of the certificate to find.</param>
        /// <returns>The context for the matching certificate.</returns>
        private static async Task<IBuffer> FindCertificate(string thumbprint)
        {
            byte[] byteThumbprint = new byte[thumbprint.Length];
            for (int i = 0; i < thumbprint.Length; i++)
            {
                byteThumbprint[i] = (byte)thumbprint[i];
            }

            CertificateQuery query = new CertificateQuery();
            query.Thumbprint = byteThumbprint;
            IReadOnlyList<Certificate> list = await CertificateStores.FindAllAsync(query);
            if (list.Count > 0)
            {
                return list[0].GetCertificateBlob();
            }
            else
            {
                return null;
            }
        }
Exemplo n.º 18
0
        private async void DoGet(bool ignoreCertErrors, string key, string value, string friendlyName)
        {
            ResponseHeadersBlock.Text = String.Empty;
            CertErrorsBlock.Text = String.Empty;
            ResponseContentBlock.Text = String.Empty;

            HttpRequestMessage request = null;
            try
            {
                request = new HttpRequestMessage(
                    HttpMethod.Get,
                    new Uri(UriBox2.Text));

                HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();

                if (ignoreCertErrors)
                {
                    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
                    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
                    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.RevocationFailure);
                }

                if (!String.IsNullOrEmpty(friendlyName))
                {
                    CertificateQuery query = new CertificateQuery();
                    query.FriendlyName = friendlyName;
                    IReadOnlyCollection<Certificate> certs = await CertificateStores.FindAllAsync(query);
                    filter.ClientCertificate = certs.ElementAt(0);
                }

                HttpClient client = new HttpClient(filter);
                
                if (!String.IsNullOrEmpty(key))
                {
                    client.DefaultRequestHeaders.Add(key, value);
                }

                HttpResponseMessage response = await client.SendRequestAsync(request);

                ResponseHeadersBlock.Text = response.ReasonPhrase;
                ResponseContentBlock.Text = await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                ResponseHeadersBlock.Text = ex.ToString();

                // Something like: 'Untrusted, InvalidName, RevocationFailure'
                CertErrorsBlock.Text = String.Join(
                    ", ",
                    request.TransportInformation.ServerCertificateErrors);
            }
        }