/// <summary>
        /// Import an existing pfx certificate
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ImportPfx_Click(object sender, RoutedEventArgs e)
        {
            TextBlock outputTextBlock = rootPage.FindName("OutputTextBlock") as TextBlock;

            try
            {
                outputTextBlock.Text = "Importing PFX certificate ...";

                // Load the pfx certificate from resource string.
                ResourceLoader rl             = new ResourceLoader();
                string         pfxCertificate = rl.GetString("Certificate");

                string password     = "******"; //password to access the certificate in PFX format
                string friendlyName = "test pfx certificate";

                //call Certificate Enrollment funciton importPFXData to install the certificate
                await CertificateEnrollmentManager.ImportPfxDataAsync(pfxCertificate,
                                                                      password,
                                                                      ExportOption.NotExportable,
                                                                      KeyProtectionLevel.NoConsent,
                                                                      InstallOptions.None,
                                                                      friendlyName);

                outputTextBlock.Text += "\nCertificate installation succeeded. The certificate is in the appcontainer Personal certificate store";
            }
            catch (Exception ex)
            {
                outputTextBlock.Text += "\nCertificate installation failed with error: " + ex.ToString();
            }
        }
        /*
         * Private Helper method
         * will import certificate into App's key store
         */
        private async Task <Certificate> ImportCertificateHelperAsync(string certFolder, string certFileName)
        {
            StorageFolder packageLocation   = Windows.ApplicationModel.Package.Current.InstalledLocation;
            StorageFolder certificateFolder = await packageLocation.GetFolderAsync(certFolder);

            StorageFile certificate = await certificateFolder.GetFileAsync(certFileName);

            IBuffer buffer = await Windows.Storage.FileIO.ReadBufferAsync(certificate);

            string encodedString = Windows.Security.Cryptography.CryptographicBuffer.EncodeToBase64String(buffer);

            System.Diagnostics.Debug.WriteLine("Encoded Certificate: " + encodedString);

            await CertificateEnrollmentManager.ImportPfxDataAsync(
                encodedString,
                certificatePassword,
                ExportOption.NotExportable,
                KeyProtectionLevel.NoConsent,
                InstallOptions.DeleteExpired,
                "userCert");

            IReadOnlyList <Windows.Security.Cryptography.Certificates.Certificate> certs = await Windows.Security.Cryptography.Certificates.CertificateStores.FindAllAsync(new Windows.Security.Cryptography.Certificates.CertificateQuery()
            {
                FriendlyName = "userCert"
            });

            this.certificate = certs.FirstOrDefault();

            System.Diagnostics.Debug.WriteLine("Certificate ready for user (CN): " + this.certificate.Subject);

            return(certs.FirstOrDefault());
        }
Esempio n. 3
0
        private async Task AddToWinCertStore()
        {
            Pkcs12Store store        = new Pkcs12Store();
            string      friendlyName = "Limelight-Client";
            var         certEntry    = new X509CertificateEntry(cert);

            store.SetCertificateEntry(friendlyName, certEntry);

            var keyEntry = new AsymmetricKeyEntry(keyPair.Private);

            store.SetKeyEntry(friendlyName, keyEntry, new[] { certEntry });

            // Copy the Pkcs12Store to a stream using an arbitrary password
            const string password = "******";
            var          stream   = new MemoryStream();

            store.Save(stream, password.ToCharArray(), new SecureRandom());

            // Write to .PFX string
            byte[] arr = stream.ToArray();

            IBuffer buf = arr.AsBuffer();
            string  pfx = CryptographicBuffer.EncodeToBase64String(buf);

            await CertificateEnrollmentManager.ImportPfxDataAsync(pfx, password, ExportOption.NotExportable, KeyProtectionLevel.NoConsent, InstallOptions.None, friendlyName);
        }
        private async Task <Certificate> InstallClientCertificateAsync()
        {
            // Load the certificate from the clientCert.pfx file packaged with this sample.
            // This certificate has been signed with a trusted root certificate installed on the server.
            // The installation is done by running the setupServer.ps1 file, which should have been done
            // before running the app.
            // WARNING: Including a pfx file in the app package violates the Windows Store
            // certification requirements. We are shipping the pfx file with the package for demonstrating
            // the usage of client certificates. Apps that will be published through Windows Store
            // need to use other approaches to obtain a client certificate.
            StorageFile clientCertFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(ClientCertUriPath));

            IBuffer buffer = await FileIO.ReadBufferAsync(clientCertFile);

            AppendOutputLine("Reading certificate succeeded.");

            string clientCertData = Windows.Security.Cryptography.CryptographicBuffer.EncodeToBase64String(buffer);

            try
            {
                // Install the certificate to the app's certificate store.
                // The app certificate store is removed when the app is uninstalled.

                //To install a certificate to the CurrentUser\MY store, which is not app specific,
                // you need to use CertificateEnrollmentManager.UserCertificateEnrollmentManager.ImportPfxDataAsync().
                // In order to call that method, an app must have the "sharedUserCertificates" capability.
                // There are two ways to add this capability:
                //
                // 1. You can double click on the Package.appxmanifest file from the
                // solution explorer, select the "Capabilities" tab in the opened page, and then check the
                // "Shared User Certificates" box from the capabilities list.
                // 2. You can right click on the Package.appxmanifest file from the
                // solution explorer, select "View Code", and add "sharedUserCertificates" under the <Capabilities>
                // element directly.
                // Package.appxmanifest in this sample shows this capability commented out.
                //
                // The certificate will remain even when the app is uninstalled.
                await CertificateEnrollmentManager.ImportPfxDataAsync(
                    clientCertData,
                    ClientCertPassword,
                    ExportOption.Exportable,
                    KeyProtectionLevel.NoConsent,
                    InstallOptions.DeleteExpired,
                    ClientCertFriendlyName);

                AppendOutputLine("Installing certificate succeeded.");

                // Return the certificate we just instaled.
                return(await FindCertificateFromStoreAsync());
            }
            catch (Exception ex)
            {
                // This can happen if the certificate has already expired.
                AppendOutputLine("Installing certificate failed with" + ex.Message);
                return(null);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Import an existing pfx certificate
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void RunSample_Click(object sender, RoutedEventArgs e)
        {
            CheckBox    storeSelectionCheckbox = rootPage.FindName("UserStoreCheckBox") as CheckBox;
            TextBlock   outputTextBlock        = rootPage.FindName("OutputTextBlock") as TextBlock;
            PasswordBox pfxPasswordBox         = rootPage.FindName("PfxPasswordBox") as PasswordBox;

            if (String.IsNullOrEmpty(pfxCertificate))
            {
                outputTextBlock.Text = "Please select a valid PFX file\n";
                return;
            }

            try
            {
                // Import PFX
                outputTextBlock.Text = "Importing PFX certificate ...";

                string friendlyName = "test pfx certificate";
                pfxPassword = pfxPasswordBox.Password;

                if (true == storeSelectionCheckbox.IsChecked)
                {
                    // target store is User's Certificate Store
                    // call User Certificate Enrollment function importPfxData to install the certificate
                    await CertificateEnrollmentManager.UserCertificateEnrollmentManager.ImportPfxDataAsync(
                        pfxCertificate,
                        pfxPassword,
                        ExportOption.NotExportable,
                        KeyProtectionLevel.NoConsent,
                        InstallOptions.None,
                        friendlyName);

                    outputTextBlock.Text += "\nCertificate installation succeeded. The certificate is in the User's certificate store";
                }
                else
                {
                    // target store is App's certificate store
                    // call Certificate Enrollment function importPFXData to install the certificate
                    await CertificateEnrollmentManager.ImportPfxDataAsync(
                        pfxCertificate,
                        pfxPassword,
                        ExportOption.NotExportable,
                        KeyProtectionLevel.NoConsent,
                        InstallOptions.None,
                        friendlyName);

                    outputTextBlock.Text += "\nCertificate installation succeeded. The certificate is in the App's certificate store";
                }
            }
            catch (Exception ex)
            {
                outputTextBlock.Text += "\nCertificate installation failed with error: " + ex.ToString();
            }
        }
Esempio n. 6
0
        private async Task <string> CreteRequest()
        {
            CertificateRequestProperties certRequestProperties = new CertificateRequestProperties();

            certRequestProperties.Exportable         = ExportOption.NotExportable;
            certRequestProperties.FriendlyName       = "Bigsby Client";
            certRequestProperties.KeyProtectionLevel = KeyProtectionLevel.NoConsent;
            certRequestProperties.KeyUsages          = EnrollKeyUsages.Signing;
            certRequestProperties.Subject            = "BigsbyClient";

            return(await CertificateEnrollmentManager.CreateRequestAsync(certRequestProperties));
        }
Esempio n. 7
0
        private async void SetClientCertificate(ClientCertificate certificate)
        {
            if (certificate == null)
            {
                return;
            }

            this.ClientCertificateOptions = ClientCertificateOption.Automatic;

            await CertificateEnrollmentManager.ImportPfxDataAsync(certificate.RawData,
                                                                  certificate.Passphrase,       // the password is blank, but you can specify one here
                                                                  ExportOption.NotExportable,   // there is no reason to keep the certificate Exportable
                                                                  KeyProtectionLevel.NoConsent, // whether any consent is required
                                                                  InstallOptions.DeleteExpired, // no installation options
                                                                  Package.Current.DisplayName);
        }
Esempio n. 8
0
        public async Task InstallAsync(string certResponse)
        {
            #region Bouncy castle PKCS #12 cert file generation
            var data = Convert.FromBase64String(certResponse);

            var parser = new X509CertificateParser();
            var cert   = parser.ReadCertificate(data);

            Pkcs12Store          store     = new Pkcs12StoreBuilder().Build();
            X509CertificateEntry certEntry = new X509CertificateEntry(cert);
            store.SetCertificateEntry(cert.SubjectDN.ToString(), certEntry); // use DN as the Alias.

            AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(_privateKey);
            store.SetKeyEntry(cert.SubjectDN.ToString() + "_key", keyEntry, new X509CertificateEntry[] { certEntry }); //

            string pfx      = string.Empty;
            string password = "";
            using (MemoryStream ms = new MemoryStream())
            {
                store.Save(ms, password.ToCharArray(), _random);

                ms.Position = 0;
                await _storage.SetAsync("accessCert", ms.GetWindowsRuntimeBuffer());

                StreamReader streamReader = new StreamReader(ms);
                // Write to .PFX string
                byte[] arr = ms.ToArray();

                pfx = CryptographicBuffer.EncodeToBase64String(arr.AsBuffer());
            }
            #endregion
            await _storage.SetAsync(StorageKeyNames.PrivateKey, pfx);

            await CertificateEnrollmentManager.ImportPfxDataAsync(pfx, password, ExportOption.NotExportable, KeyProtectionLevel.NoConsent, InstallOptions.None, "MAG_CERT");

            // Store the registered cert subject
            if (cert.SubjectDN != null)
            {
                var valueList = cert.SubjectDN.GetValueList(X509Name.CN);
                if (valueList.Count > 0)
                {
                    await _storage.SetAsync(StorageKeyNames.RegisteredCertSubject, (string)valueList[0]);
                }
            }
        }
Esempio n. 9
0
        private static async Task InstallCertificate(string filePath, string friendlyName)
        {
            //string certPath = @"Assets\BigsbyClientCert.pfx";
            StorageFile file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(filePath);

            IBuffer buffer = await FileIO.ReadBufferAsync(file);

            string certData = CryptographicBuffer.EncodeToBase64String(buffer);

            // Will ask the user if they want this app to install the certificate if its not already installed.
            await CertificateEnrollmentManager.ImportPfxDataAsync(
                certData,
                "",
                ExportOption.NotExportable,
                KeyProtectionLevel.NoConsent,
                InstallOptions.None,
                friendlyName);
        }
Esempio n. 10
0
        public async Task <Certificate> GetIfExistsAsync()
        {
            var Certificate = await GetAsync();

            try
            {
                if (Certificate == null)
                {
                    string pfx = await _storage.GetTextAsync(StorageKeyNames.PrivateKey);

                    if (pfx != null)
                    {
                        await CertificateEnrollmentManager.ImportPfxDataAsync(pfx, string.Empty, ExportOption.NotExportable, KeyProtectionLevel.NoConsent, InstallOptions.None, "MAG_CERT");
                    }
                    Certificate = await GetAsync();
                }
            }
            catch (Exception)
            {
            }
            return(Certificate);
        }
Esempio n. 11
0
        /// <summary>
        /// Create a certificate request
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void CreateRequest_Click(object sender, RoutedEventArgs e)
        {
            TextBlock outputTextBlock = rootPage.FindName("OutputTextBlock") as TextBlock;

            outputTextBlock.Text = "Creating certificate request...";

            try
            {
                //call the default constructor of CertificateRequestProperties
                CertificateRequestProperties reqProp = new CertificateRequestProperties();
                reqProp.Subject      = "Toby";
                reqProp.FriendlyName = "Toby's Cert";

                //call Certificate Enrollment function createRequest to create a certificate request
                certificateRequest = await CertificateEnrollmentManager.CreateRequestAsync(reqProp);

                outputTextBlock.Text += "\nRequest created, content:\n" + certificateRequest;
            }
            catch (Exception ex)
            {
                outputTextBlock.Text += "\n\nCertificate request creation failed with error: " + ex.Message;
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Basic settings are configured on the view that is attached to this VM.
        /// </summary>
        /// <param name="screen"></param>
        public BasicSettingsViewModel(IScreen screen)
        {
            HostScreen = screen;

            // Look for a currently loaded cert and update the status...
            // We can't start this b.c. the ToProperty is lazy - and it won't
            // fire until Status is data-bound!
            LookupCertStatus = ReactiveCommand.CreateAsyncTask(a => SecurityUtils.FindCert(SecurityUtils.CERNCertName));
            LookupCertStatus
            .Select(c => c == null ? "No Cert Loaded" : string.Format("Loaded (expires {0})", c.ValidTo.ToLocalTime().ToString("yyyy-MM-dd HH:mm")))
            .ToProperty(this, x => x.Status, out _status, "", RxApp.MainThreadScheduler);

            LookupCertStatus
            .ExecuteAsync()
            .Subscribe();

            // Error and status messages...
            var errors = new Subject <string>();

            errors
            .ToProperty(this, x => x.Error, out _error, "", RxApp.MainThreadScheduler);

            // Given a file and a password, see if we can install it as a cert
            // in our internal repository.
            LoadFiles = ReactiveCommand.Create();
            LoadFiles
            .Subscribe(x => errors.OnNext(""));

            var files = LoadFiles
                        .Cast <Tuple <IReadOnlyList <StorageFile>, string> >();

            files
            .Where(finfo => finfo.Item1 == null || finfo.Item1.Count != 1)
            .Select(f => "Invalid certificate file")
            .Subscribe(errors);

            files
            .Where(finfo => finfo.Item1 != null && finfo.Item1.Count == 1)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Select(mf =>
            {
                // We use this double subscribe because the readBufferAsync and ImportPfxDataAsync often return exceptions.
                // If we let the exception bubble all the way up, it terminates the sequence. Which means if the user entered
                // the wrong password they wouldn't get a chance to try again!
                return(Observable.Return(mf)
                       .SelectMany(async f =>
                {
                    // 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);

                    var fs = f.Item1[0] as StorageFile;
                    var buffer = await FileIO.ReadBufferAsync(fs);
                    var cert = CryptographicBuffer.EncodeToBase64String(buffer);

                    await CertificateEnrollmentManager.ImportPfxDataAsync(cert, f.Item2, ExportOption.NotExportable, KeyProtectionLevel.NoConsent, InstallOptions.DeleteExpired, SecurityUtils.CERNCertName);
                    return Unit.Default;
                }));
            })
            .Subscribe(c => c.Subscribe(
                           g => LookupCertStatus.ExecuteAsync().Subscribe(),
                           e => errors.OnNext(e.Message.TakeFirstLine())
                           ));

            // Set/Get the file expiration policy.
            CacheDecayOptions = ExpirationOptions.GetListExpirationOptions();

            // Get the list of indico api keys we are watching
            // and hook up the MV for doing the api key manipulation
            ApiKeysForIndico = new ReactiveList <IndicoApiKey>();
            ApiKeysForIndico.AddRange(IndicoApiKeyAccess.LoadAllKeys());
            IndicoApiKeyAccess.IndicoApiKeysUpdated
            .Subscribe(_ =>
            {
                using (ApiKeysForIndico.SuppressChangeNotifications())
                {
                    ApiKeysForIndico.Clear();
                    ApiKeysForIndico.AddRange(IndicoApiKeyAccess.LoadAllKeys());
                }
            });

            ShowIndicoApiKey = ReactiveCommand.Create();
            ShowIndicoApiKey
            .Cast <IndicoApiKey>()
            .Select(x => new AddOrUpdateIndicoApiKeyViewModel(x))
            .ToProperty(this, x => x.IndicoApiKey, out _indicoApiKeyVM, new AddOrUpdateIndicoApiKeyViewModel(null));
        }