Пример #1
0
        /// <summary>
        /// Creates a Passport key on the machine using the _account id passed.
        /// </summary>
        /// <param name="accountId">The _account id associated with the _account that we are enrolling into Passport</param>
        /// <returns>Boolean representing if creating the Passport key succeeded</returns>
        public static async Task <bool> CreatePassportKeyAsync(string accountId)
        {
            KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync(accountId, KeyCredentialCreationOption.ReplaceExisting);

            switch (keyCreationResult.Status)
            {
            case KeyCredentialStatus.Success:
                // In the real world authentication would take place on a server.
                // So every time a user migrates or creates a new Microsoft Passport account Passport details should be pushed to the server.
                // The details that would be pushed to the server include:
                // The public key, keyAttesation if available,
                // certificate chain for attestation endorsement key if available,
                // status code of key attestation result: keyAttestationIncluded or
                // keyAttestationCanBeRetrievedLater and keyAttestationRetryType
                // As this sample has no concept of a server it will be skipped for now
                // for information on how to do this refer to the second Passport sample

                //For this sample just return true
                return(true);

            case KeyCredentialStatus.UserCanceled:
                //Debug.WriteLine("User cancelled sign-in process.");
                break;

            case KeyCredentialStatus.NotFound:
                // User needs to setup Microsoft Passport
                //Debug.WriteLine("Microsoft Passport is not setup!\nPlease go to Windows Settings and set up a PIN to use it.");
                break;

            default:
                break;
            }

            return(false);
        }
        /// <summary>
        /// 请求注册用户
        /// </summary>
        /// <returns></returns>
        public static async Task <AuthenticatorState> RegisterUserAsync()
        {
            if (await CheckSupportAsync().ConfigureAwait(false))
            {
                KeyCredentialRetrievalResult CredentiaResult = await KeyCredentialManager.RequestCreateAsync(CredentialName, KeyCredentialCreationOption.ReplaceExisting);

                switch (CredentiaResult.Status)
                {
                case KeyCredentialStatus.Success:
                {
                    string PublicKey = CryptographicBuffer.EncodeToHexString(CredentiaResult.Credential.RetrievePublicKey());
                    ApplicationData.Current.LocalSettings.Values["WindowsHelloPublicKeyForUser"] = PublicKey;
                    return(AuthenticatorState.RegisterSuccess);
                }

                case KeyCredentialStatus.UserCanceled:
                {
                    return(AuthenticatorState.UserCanceled);
                }

                default:
                {
                    return(AuthenticatorState.UnknownError);
                }
                }
            }
            else
            {
                return(AuthenticatorState.WindowsHelloUnsupport);
            }
        }
Пример #3
0
        public static async Task <bool> Login()
        {
            var result = await KeyCredentialManager.IsSupportedAsync();

            String message;

            if (result)
            {
                var authenticationResult = await KeyCredentialManager.RequestCreateAsync("login", KeyCredentialCreationOption.ReplaceExisting);

                if (authenticationResult.Status == KeyCredentialStatus.Success)
                {
                    message = "User is logged in";
                }
                else
                {
                    message = "Login error: " + authenticationResult.Status;
                }
            }
            else
            {
                message = "Windows Hello is not enabled for this device.";
            }

            String imagePath = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
            String xml       = "<toast><visual><binding template='ToastGeneric'><text hint-maxLines='1'>" + message + "</text></binding></visual></toast>";

            Toast.CreateToast(xml);

            return(result);
        }
Пример #4
0
        private async void tryToCloseWinHello()
        {
            KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync("WinHello", KeyCredentialCreationOption.ReplaceExisting);

            var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();

            if (keyCreationResult.Status == KeyCredentialStatus.Success)
            {
                Password.winHelloStatus = false;
                LockButton.IsEnabled    = false;
                Password.WriteWinHelloData();
            }
            else if (keyCreationResult.Status == KeyCredentialStatus.NotFound)
            {
                Password.winHelloStatus = true;
                WHToggle.IsOn           = true;
                MessageDialog message = new MessageDialog(resourceLoader.GetString("WHError1"));
                await message.ShowAsync();
            }
            else if (keyCreationResult.Status == KeyCredentialStatus.UnknownError)
            {
                Password.winHelloStatus = true;
                WHToggle.IsOn           = true;
                MessageDialog message = new MessageDialog(resourceLoader.GetString("WHError2"));
                await message.ShowAsync();
            }
            else
            {
                Password.winHelloStatus = true;
                WHToggle.IsOn           = true;
            }
        }
Пример #5
0
        /// <summary>
        /// Create a passport key
        /// </summary>
        /// <exception cref="UserCancelledException"></exception>
        /// <exception cref="MissingPinException"></exception>
        /// <exception cref="UserPrefersPasswordException"></exception>
        /// <exception cref="UnknownException"></exception>
        /// <exception cref="AggregateException"></exception>
        /// <param name="accountId">The account id</param>
        public static void CreatePassportKey(string accountId)
        {
            // Run KeyCredentialManager.RequestCreateAsync to create the account.
            // Overwrites any existing accounts
            Task <KeyCredentialRetrievalResult> task = Task.Run(async() =>
                                                                await KeyCredentialManager.RequestCreateAsync(accountId, KeyCredentialCreationOption.ReplaceExisting));

            // Check the KeyCredentialRetrievalResult status
            switch (task.Result.Status)
            {
            case KeyCredentialStatus.Success:
                // The operation was successful
                return;

            case KeyCredentialStatus.UserCanceled:
                // User cancelled the Passport enrollment process
                throw new UserCancelledException();

            case KeyCredentialStatus.NotFound:
                // User needs to create PIN
                throw new MissingPinException();

            case KeyCredentialStatus.UserPrefersPassword:
                // The user prefers a password
                throw new UserPrefersPasswordException();

            default:
                // An unknown error occurred
                throw new UnknownException();
            }
        }
Пример #6
0
        public const int ERR_CREAT_KEY_EXISTS = 170; // Avoid reserved exit codes of UNIX

        static async Task <(int err, string pubKey)> CreatePublicKey(string key_name)
        {
            int err;
            var createRes = await KeyCredentialManager.RequestCreateAsync(key_name, KeyCredentialCreationOption.FailIfExists);

            IBuffer pubKey;

            if (createRes.Status == KeyCredentialStatus.CredentialAlreadyExists)
            {
                var existing = await KeyCredentialManager.OpenAsync(key_name);

                if (existing.Status != KeyCredentialStatus.Success)
                {
                    return(ERR_CREAT_FAIL, null);
                }
                err    = ERR_CREAT_KEY_EXISTS;
                pubKey = existing.Credential.RetrievePublicKey();
            }
            else if (createRes.Status != KeyCredentialStatus.Success)
            {
                return(ERR_CREAT_FAIL, null);
            }
            else
            {
                err    = 0;
                pubKey = createRes.Credential.RetrievePublicKey();
            }
            var pem = String.Format("-----BEGIN PUBLIC KEY-----\n{0}\n-----END PUBLIC KEY-----\n", CryptographicBuffer.EncodeToBase64String(pubKey));

            return(err, pem);
        }
Пример #7
0
        public static async Task <bool> CreatePassportKeyAsync(Guid userId, string username)
        {
            KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync(username, KeyCredentialCreationOption.ReplaceExisting);

            switch (keyCreationResult.Status)
            {
            case KeyCredentialStatus.Success:
                Debug.WriteLine("Successfully made key");
                await GetKeyAttestationAsync(userId, keyCreationResult);

                return(true);

            case KeyCredentialStatus.UserCanceled:
                Debug.WriteLine("User cancelled sign-in process.");
                break;

            case KeyCredentialStatus.NotFound:
                // User needs to setup Windows Hello
                Debug.WriteLine("Windows Hello is not setup!\nPlease go to Windows Settings and set up a PIN to use it.");
                break;

            default:
                break;
            }

            return(false);
        }
Пример #8
0
        private async Task <IBuffer> CreatePassportKeyCredentialAsync()
        {
            // Create a new KeyCredential for the user on the device.
            KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync(userId, KeyCredentialCreationOption.ReplaceExisting);

            if (keyCreationResult.Status == KeyCredentialStatus.Success)
            {
                // User has autheniticated with Windows Hello and the key credential is created.
                KeyCredential userKey = keyCreationResult.Credential;
                return(userKey.RetrievePublicKey());
            }
            else if (keyCreationResult.Status == KeyCredentialStatus.NotFound)
            {
                MessageDialog message = new MessageDialog("To proceed, Windows Hello needs to be configured in Windows Settings (Accounts -> Sign-in options)");
                await message.ShowAsync();

                return(null);
            }
            else if (keyCreationResult.Status == KeyCredentialStatus.UnknownError)
            {
                MessageDialog message = new MessageDialog("The key credential could not be created. Please try again.");
                await message.ShowAsync();

                return(null);
            }

            return(null);
        }
        private async void Hello_Click(object sender, RoutedEventArgs e)
        {
            var keyCredentialAvailable = await KeyCredentialManager.IsSupportedAsync();

            var result = await KeyCredentialManager.RequestCreateAsync(Viewmodel.Username, KeyCredentialCreationOption.ReplaceExisting);

            //return public key, Attestation and Username to ASB for backend storage. Visit: https://docs.microsoft.com/en-us/windows/uwp/security/microsoft-passport for more info
            Result.TrySetResult(true);
        }
Пример #10
0
        /// <summary>
        /// Creates a Passport key on the machine using the _account id passed.
        /// </summary>
        /// <param name="accountId">The _account id associated with the _account that we are enrolling into Passport</param>
        /// <returns>Boolean representing if creating the Passport key succeeded</returns>
        public static async Task <bool> CreatePassportKeyAsync(Guid userId, string username)
        {
            Debug.WriteLine("Before calling KeyCredentialManager.RequestCreateAsync");

            KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync(username, KeyCredentialCreationOption.ReplaceExisting);

            Debug.WriteLine("After calling KeyCredentialManager.RequestCreateAsync");

            switch (keyCreationResult.Status)
            {
            case KeyCredentialStatus.Success:
                Debug.WriteLine("Successfully made key");

                // In the real world authentication would take place on a server.
                // So every time a user migrates or creates a new Microsoft Passport account Passport details should be pushed to the server.
                // The details that would be pushed to the server include:
                // The public key, keyAttesation if available,
                // certificate chain for attestation endorsement key if available,
                // status code of key attestation result: keyAttestationIncluded or
                // keyAttestationCanBeRetrievedLater and keyAttestationRetryType
                // As this sample has no concept of a server it will be skipped for now
                // for information on how to do this refer to the second Passport sample

                //For this sample just return true
                await GetKeyAttestationAsync(userId, keyCreationResult);

                return(true);

            case KeyCredentialStatus.UserCanceled:
                Debug.WriteLine("User cancelled sign-in process.");
                break;

            case KeyCredentialStatus.NotFound:
                // User needs to setup Microsoft Passport
                Debug.WriteLine("Microsoft Passport is not setup!\nPlease go to Windows Settings and set up a PIN to use it.");
                break;

            case KeyCredentialStatus.CredentialAlreadyExists:
                Debug.WriteLine("Credential already exists!");
                break;

            case KeyCredentialStatus.UnknownError:
                Debug.WriteLine("Unknown error generating credentials key");
                break;

            default:
                Debug.WriteLine("Some error making the credentials key!");
                break;
            }

            return(false);
        }
        public static async Task <bool> CreatePassportKeyAsync()
        {
            KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync("temp", KeyCredentialCreationOption.ReplaceExisting);

            if (keyCreationResult.Status == KeyCredentialStatus.Success)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #12
0
        /// <summary>
        /// Creates a Passport key on the machine using the account id passed.
        /// Then returns a boolean based on whether we were able to create a Passport key or not.
        ///
        /// Will also attempt to create an attestation that this key is backed by hardware on the device, but is not a requirement
        /// for a working key in this scenario. It is possible to not accept a key that is software-based only.
        /// </summary>
        /// <param name="accountId">The account id associated with the account that we are enrolling into Passport</param>
        /// <returns>Boolean representing if creating the Passport key succeeded</returns>
        public async Task <bool> CreatePassportKey(string accountId)
        {
            KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync(accountId, KeyCredentialCreationOption.ReplaceExisting);

            if (keyCreationResult.Status == KeyCredentialStatus.Success)
            {
                KeyCredential userKey   = keyCreationResult.Credential;
                IBuffer       publicKey = userKey.RetrievePublicKey();
                KeyCredentialAttestationResult keyAttestationResult = await userKey.GetAttestationAsync();

                if (keyAttestationResult.Status == KeyCredentialAttestationStatus.Success)
                {
                    //keyAttestation Included.
                    //TODO:read  keyAttestationResult.AttestationBuffer and keyAttestationResult.CertificateChainBuffer
                }
                else if (keyAttestationResult.Status == KeyCredentialAttestationStatus.TemporaryFailure)
                {
                    //keyAttestation CanBeRetrievedLater
                }
                else if (keyAttestationResult.Status == KeyCredentialAttestationStatus.NotSupported)
                {
                    //keyAttestation is not supported
                }

                // Package public key, keyAttesation if available,
                // certificate chain for attestation endorsement key if available,
                // status code of key attestation result: keyAttestationIncluded or
                // keyAttestationCanBeRetrievedLater and keyAttestationRetryType
                // and send it to application server to register the user.
                bool serverAddedPassportToAccount = await AddPassportToAccountOnServer();

                if (serverAddedPassportToAccount == true)
                {
                    return(true);
                }
            }
            else if (keyCreationResult.Status == KeyCredentialStatus.UserCanceled)
            {
                // User cancelled the Passport enrollment process
            }
            else if (keyCreationResult.Status == KeyCredentialStatus.NotFound)
            {
                // User needs to create PIN
                return(false);
            }
            return(false);
        }
Пример #13
0
        public async void Load()
        {
            try
            {
                if (await KeyCredentialManager.IsSupportedAsync())
                {
                    var result = await KeyCredentialManager.OpenAsync(Helper.AppName);

                    if (result.Credential != null)
                    {
                        var signResult = await result.Credential.RequestSignAsync(CryptographicBuffer.ConvertStringToBinary(DeviceHelper.PackageName, BinaryStringEncoding.Utf8));

                        if (signResult.Status == KeyCredentialStatus.Success)
                        {
                            Unlock();
                        }
                        else
                        {
                            BiometricsButton.Visibility = Visibility.Visible;
                        }
                    }
                    else
                    {
                        var creationResult = await KeyCredentialManager.RequestCreateAsync(Helper.AppName, KeyCredentialCreationOption.ReplaceExisting);

                        if (creationResult.Status == KeyCredentialStatus.Success)
                        {
                            Unlock();
                        }
                        else
                        {
                            BiometricsButton.Visibility = Visibility.Visible;
                        }
                    }
                }
                else
                {
                    PassText.Focus(FocusState.Keyboard);
                }
            }
            catch { }
        }
Пример #14
0
        private async void BiometricsButtonClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (await KeyCredentialManager.IsSupportedAsync())
                {
                    var creationResult = await KeyCredentialManager.RequestCreateAsync(Helper.AppName, KeyCredentialCreationOption.ReplaceExisting);

                    if (creationResult.Status == KeyCredentialStatus.Success)
                    {
                        Unlock();
                    }
                    else
                    {
                        BiometricsButton.Visibility = Visibility.Visible;
                    }
                }
            }
            catch { }
        }
Пример #15
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync("WinHello", KeyCredentialCreationOption.ReplaceExisting);

            var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();

            if (keyCreationResult.Status == KeyCredentialStatus.Success)
            {
                this.Frame.Navigate(typeof(MainPage));
            }
            else if (keyCreationResult.Status == KeyCredentialStatus.NotFound)
            {
                MessageDialog message = new MessageDialog(resourceLoader.GetString("WHError1"));
                await message.ShowAsync();
            }
            else if (keyCreationResult.Status == KeyCredentialStatus.UnknownError)
            {
                MessageDialog message = new MessageDialog(resourceLoader.GetString("WHError2"));
                await message.ShowAsync();
            }
        }
Пример #16
0
        private async Task <IBuffer> CreatePassportKeyCredentialAsync(string userName)
        {
            // Create a new KeyCredential for the user on the device
            var keyCreationResult = await KeyCredentialManager.RequestCreateAsync(userName, KeyCredentialCreationOption.ReplaceExisting);

            if (keyCreationResult.Status == KeyCredentialStatus.Success)
            {
                // User has autheniticated with Windows Hello and the key credential is created
                var credential = keyCreationResult.Credential;
                return(credential.RetrievePublicKey());
            }
            else if (keyCreationResult.Status == KeyCredentialStatus.NotFound)
            {
                await DialogBox.ShowAsync("Windows Hello", "To proceed, Windows Hello needs to be configured in Windows Settings (Accounts -> Sign-in options)");
            }
            else if (keyCreationResult.Status == KeyCredentialStatus.UnknownError)
            {
                await DialogBox.ShowAsync("Windows Hello Error", "The key credential could not be created. Please try again.");
            }

            return(null);
        }
Пример #17
0
        private async void Biometrics_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var result = await KeyCredentialManager.OpenAsync(Strings.Resources.AppName);

                if (result.Credential != null)
                {
                    var signResult = await result.Credential.RequestSignAsync(CryptographicBuffer.ConvertStringToBinary(Package.Current.Id.Name, BinaryStringEncoding.Utf8));

                    if (signResult.Status == KeyCredentialStatus.Success)
                    {
                        Unlock();
                    }
                    else
                    {
                        Field.Focus(FocusState.Keyboard);
                    }
                }
                else
                {
                    var creationResult = await KeyCredentialManager.RequestCreateAsync(Strings.Resources.AppName, KeyCredentialCreationOption.ReplaceExisting);

                    if (creationResult.Status == KeyCredentialStatus.Success)
                    {
                        Unlock();
                    }
                    else
                    {
                        Field.Focus(FocusState.Keyboard);
                    }
                }
            }
            catch
            {
                Field.Focus(FocusState.Keyboard);
            }
        }
Пример #18
0
        public static async Task <bool> CreatePassportKeyAsync(string accountId)
        {
            KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync(accountId, KeyCredentialCreationOption.ReplaceExisting);

            switch (keyCreationResult.Status)
            {
            case KeyCredentialStatus.Success:
                Debug.WriteLine("Successfully made key");
                return(true);

            case KeyCredentialStatus.UserCanceled:
                Debug.WriteLine("User cancelled sign-in process.");
                break;

            case KeyCredentialStatus.NotFound:
                Debug.WriteLine("Microsoft Passport is not setup!\nPlease go to Windows Settings and set up a PIN to use it.");
                break;

            default:
                break;
            }
            return(false);
        }
Пример #19
0
        public async Task <bool> AuthenticateAsync()
        {
            // Waits that the app's window gets the focus. This allows to avoid having the icon in the task bar
            // blinking orange when windows hello starts. It might distracts the user.
            await _windowFocusAwaiter.Task.ConfigureAwait(false);

            if (!await IsWindowsHelloEnabledAsync()
                .ConfigureAwait(true)) // run on the current context.
            {
                _logger.LogEvent(AuthenticateEvent, "Success == False; Windows Hello isn't enabled.");
                return(false);
            }

            // Get credentials for current user and app
            KeyCredentialRetrievalResult result = await KeyCredentialManager.OpenAsync(KeyCredentialManagerName);

            if (result.Credential != null)
            {
                // Prompt the user to authenticate.
                KeyCredentialOperationResult signResult = await result.Credential.RequestSignAsync(CryptographicBuffer.ConvertStringToBinary(KeyCredentialManagerName, BinaryStringEncoding.Utf8));

                if (signResult.Status == KeyCredentialStatus.Success)
                {
                    _logger.LogEvent(AuthenticateEvent, "Success == True");
                    return(true);
                }

                _logger.LogEvent(AuthenticateEvent, "Success == False");
                return(false);
            }

            // No previous saved credentials found, let's create them (this will also prompt the user to authenticate).
            KeyCredentialRetrievalResult creationResult = await KeyCredentialManager.RequestCreateAsync(KeyCredentialManagerName, KeyCredentialCreationOption.ReplaceExisting);

            _logger.LogEvent(AuthenticateEvent, $"Success == {creationResult.Status == KeyCredentialStatus.Success}");
            return(creationResult.Status == KeyCredentialStatus.Success);
        }
        private static async Task <bool> AuthenticateUsingWindowsHello()
        {
            if (await KeyCredentialManager.IsSupportedAsync())
            {
                // Get credentials for current user and app
                var result = await KeyCredentialManager.OpenAsync("GitIt-Hello");

                if (result.Credential != null)
                {
                    var signResult =
                        await result.Credential.RequestSignAsync(CryptographicBuffer.ConvertStringToBinary("LoginAuth",
                                                                                                           BinaryStringEncoding.Utf8));

                    return(signResult.Status == KeyCredentialStatus.Success);
                }

                // If no credentials found create one
                var creationResult = await KeyCredentialManager.RequestCreateAsync("GitIt-Hello",
                                                                                   KeyCredentialCreationOption.ReplaceExisting);

                return(creationResult.Status == KeyCredentialStatus.Success);
            }
            return(false);
        }
Пример #21
0
        private async Task <PasswordInfoModel> GetPasswordInfoModelAsync()
        {
            PasswordInfoModel model = null;
            var pwInfoFile          = await _storageService.GetCachedTextFileAsync(FileName);

            if (pwInfoFile != null)
            {
                model = JsonConvert.DeserializeObject <PasswordInfoModel>(pwInfoFile);
            }

            if (model == null)
            {
                if (!await KeyCredentialManager.IsSupportedAsync())
                {
                    return(null);
                }

                model = new PasswordInfoModel
                {
                    KeyPhrase = "sign this keyphrase of this bookmarked application to get a secure string"
                };
                var keyCreationResult =
                    await KeyCredentialManager.RequestCreateAsync(AccountId, KeyCredentialCreationOption.ReplaceExisting);

                if (keyCreationResult.Status == KeyCredentialStatus.Success)
                {
                    model.PreferPassword = false;
                }
                else if (keyCreationResult.Status == KeyCredentialStatus.UserPrefersPassword)
                {
                    model.PreferPassword = true;
                }
                await _storageService.SetCachedTextFileAsync(FileName, JsonConvert.SerializeObject(model));
            }
            return(model);
        }
Пример #22
0
        private async void Path_Auth()
        {
            // check if KeyCredentialManager can be used
            if (await KeyCredentialManager.IsSupportedAsync() == false)
            {
                await(new MessageDialog("KeyCredentialManager not supported")).ShowAsync();
                return;
            }

            // retrieve private key for sign
            KeyCredentialRetrievalResult res =
                await KeyCredentialManager.OpenAsync("key1");

            if (res.Status == KeyCredentialStatus.Success)
            {
                //
                // If it is present, we request sign for some data
                //

                // convert string to binary buffer
                var inputbuf =
                    CryptographicBuffer.ConvertStringToBinary(
                        "Test Data 1", BinaryStringEncoding.Utf8);

                // sign using retrieved private key
                // (Windows Hello is diplayed here !)
                KeyCredentialOperationResult signRes = await res.Credential.RequestSignAsync(inputbuf);

                //KeyCredentialAttestationResult signRes = await res.Credential.GetAttestationAsync();

                /*
                 * // get the base64 encoded data to cryptographically sign
                 * string base64encSignature =
                 * CryptographicBuffer.EncodeToBase64String(signRes.Result);
                 * await (new MessageDialog(base64encSignature)).ShowAsync();
                 */
                if (signRes.Status == KeyCredentialStatus.Success)
                {
                    // ナビゲーション フレームを使用して前のページに戻ります
                    if (this.Frame != null && this.Frame.CanGoBack)
                    {
                        this.Frame.GoBack();
                    }
                    else if (this.Frame != null)
                    {
                        //this.Frame.Navigate(typeof(Browser.MainBrowser));
                        this.Frame.Navigate(typeof(Browser.Browser1));
                    }
                }
                else
                {
                    // get the base64 encoded data to cryptographically sign
                    //string base64encSignature = CryptographicBuffer.EncodeToBase64String(signRes.Result);
                    await(new MessageDialog("キャンセルしました")).ShowAsync();
                    //await (new MessageDialog(base64encSignature)).ShowAsync();
                }
            }
            else if (res.Status == KeyCredentialStatus.NotFound)
            {
                //
                // If the credential is not found, we create it.
                //

                // Create the credential
                // (Windows Hello is diplayed here !)
                KeyCredentialRetrievalResult createRes =
                    await KeyCredentialManager.RequestCreateAsync("key1",
                                                                  KeyCredentialCreationOption.ReplaceExisting);

                if (createRes.Status == KeyCredentialStatus.Success)
                {
                    // ナビゲーション フレームを使用して前のページに戻ります
                    if (this.Frame != null && this.Frame.CanGoBack)
                    {
                        this.Frame.GoBack();
                    }
                    else if (this.Frame != null)
                    {
                        //this.Frame.Navigate(typeof(Browser.MainBrowser));
                        this.Frame.Navigate(typeof(Browser.Browser1));
                    }
                }
                else
                {
                    // get the base64 encoded data to cryptographically sign
                    //string base64encSignature = CryptographicBuffer.EncodeToBase64String(signRes.Result);
                    await(new MessageDialog("キャンセルしました")).ShowAsync();
                    //await (new MessageDialog(base64encSignature)).ShowAsync();
                }

                /*
                 * // if the status is success, retrieve the public key.
                 * if (createRes.Status == KeyCredentialStatus.Success)
                 * {
                 * var pubKey = createRes.Credential.RetrievePublicKey();
                 * AsymmetricKeyAlgorithmProvider alg =
                 *  AsymmetricKeyAlgorithmProvider.OpenAlgorithm(
                 *    AsymmetricAlgorithmNames.RsaPkcs1);
                 * CryptographicKey ckey = alg.ImportPublicKey(pubKey);
                 * // for ex, CryptographicEngine.VerifySignature() using this CryptographicKey
                 * // (This time, just showing the keysize)
                 * var dialog = new MessageDialog(string.Format("Key size is {0}", ckey.KeySize));
                 * await dialog.ShowAsync();
                 * }
                 */
            }
            else
            {
                await(new MessageDialog("Unknown error !")).ShowAsync();
            }
        }
Пример #23
0
        private async void btnTest_Click(object sender, RoutedEventArgs e)
        {
            var keyCredentialAvailable = await KeyCredentialManager.IsSupportedAsync();

            if (!keyCredentialAvailable)
            {
                // User didn't set up PIN yet
                await ShowMsg("No key credentials available");
            }

            await ShowMsg("KeyCredentials are available");

            string returnMessage = null;

            try
            {
                // Request the logged on user's consent via fingerprint swipe.
                //var consentResult = await Windows.Security.Credentials.UI.UserConsentVerifier.RequestVerificationAsync("Require you to authenticate");
                var authenticationResult = await KeyCredentialManager.RequestCreateAsync("login", KeyCredentialCreationOption.ReplaceExisting);

                var pubKeyBuffer   = authenticationResult.Credential.RetrievePublicKey();
                var pubKey         = pubKeyBuffer.ToArray();
                var pubKeyAsBase64 = Convert.ToBase64String(pubKey);

                PopulateTextFieldData(pubKeyAsBase64);

                if (authenticationResult.Status == KeyCredentialStatus.Success)
                {
                    returnMessage = "User is logged in";
                }
                else
                {
                    returnMessage = "Login error: " + authenticationResult.Status;
                }
                //switch (consentResult)
                //{
                //    case Windows.Security.Credentials.UI.UserConsentVerificationResult.Verified:
                //        returnMessage = "Fingerprint verified.";
                //        break;
                //    case Windows.Security.Credentials.UI.UserConsentVerificationResult.DeviceBusy:
                //        returnMessage = "Biometric device is busy.";
                //        break;
                //    case Windows.Security.Credentials.UI.UserConsentVerificationResult.DeviceNotPresent:
                //        returnMessage = "No biometric device found.";
                //        break;
                //    case Windows.Security.Credentials.UI.UserConsentVerificationResult.DisabledByPolicy:
                //        returnMessage = "Biometric verification is disabled by policy.";
                //        break;
                //    case Windows.Security.Credentials.UI.UserConsentVerificationResult.NotConfiguredForUser:
                //        returnMessage = "The user has no fingerprints registered. Please add a fingerprint to the " +
                //                        "fingerprint database and try again.";
                //        break;
                //    case Windows.Security.Credentials.UI.UserConsentVerificationResult.RetriesExhausted:
                //        returnMessage = "There have been too many failed attempts. Fingerprint authentication canceled.";
                //        break;
                //    case Windows.Security.Credentials.UI.UserConsentVerificationResult.Canceled:
                //        returnMessage = "Fingerprint authentication canceled.";
                //        break;
                //    default:
                //        returnMessage = "Fingerprint authentication is currently unavailable.";
                //        break;
                //}
            }
            catch (Exception ex)
            {
                returnMessage = "Fingerprint authentication failed: " + ex.ToString();
            }

            await ShowMsg(returnMessage);
        }
Пример #24
0
        private async Task <bool> CreatePassportKeyAsync()
        {
            KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync(DefaultLogin, KeyCredentialCreationOption.ReplaceExisting);

            return(this.IsCredentialValid(keyCreationResult));
        }
Пример #25
0
 /// <summary>
 /// Request the creation of a Microsoft Key credential.
 /// </summary>
 /// <param name="credentialName">Name given to the credential to be created.</param>
 /// <param name="op">Available options to request the credential creation (Fail if exists or Replace existing.</param>
 /// <returns>KeyCredentialRetrievalResult object with all the information.</returns>
 internal static async Task <KeyCredentialRetrievalResult> CreateCredential(string credentialName, KeyCredentialCreationOption op)
 {
     return(await KeyCredentialManager.RequestCreateAsync(credentialName, op));
 }
        /// <summary>
        /// Retrieve the password to use to open the given database
        /// </summary>
        /// <param name="databaseName">name of the database</param>
        /// <returns>credentials to use to open this database</returns>
        public async static Task <PasswordParameter> GetDatabasePasswordAsync(string databaseName)
        {
            PasswordParameter credentials = null;

            // Try to use Windows Hello
            if (SettingsViewModel.Instance.WindowsHelloEnabled &&
                await KeyCredentialManager.IsSupportedAsync()
                )
            {
                // Try to open an already generated Windows Hello credentials
                var passportCredentials = await KeyCredentialManager.OpenAsync(WINDOWS_HELLO_SERVICE_NAME);

                if (passportCredentials.Status == KeyCredentialStatus.Success)
                {
                    var signRes = await passportCredentials.Credential.RequestSignAsync(
                        CryptographicBuffer.ConvertStringToBinary("LoginAuth", BinaryStringEncoding.Utf8));

                    if (signRes.Status == KeyCredentialStatus.Success)
                    {
                        // User confirmed its identity, retrieve the credentials from the system Password Vault
                        try
                        {
                            credentials = await LoadDatabasePasswordAsync(databaseName);
                        }
                        catch (Exception)
                        {
                            // Prompt for credentials, then store them
                            PasswordParameter password = await ShowPasswordDialogAsync(databaseName);

                            StoreDatabasePassword(databaseName, password);
                            credentials = password;
                        }
                    }
                    else if (signRes.Status == KeyCredentialStatus.UserCanceled)
                    {
                        // User cancelled the credential
                        throw new TaskCanceledException();
                    }
                }
                else
                {
                    // No credentials available, need to create it
                    var passportCredentialCreation = await KeyCredentialManager.RequestCreateAsync(WINDOWS_HELLO_SERVICE_NAME, KeyCredentialCreationOption.FailIfExists);

                    if (passportCredentialCreation.Status == KeyCredentialStatus.Success ||
                        passportCredentialCreation.Status == KeyCredentialStatus.CredentialAlreadyExists)
                    {
                        // Prompt for credentials, then store them
                        PasswordParameter password = await ShowPasswordDialogAsync(databaseName);

                        StoreDatabasePassword(databaseName, password);
                        credentials = password;
                    }
                    else if (passportCredentialCreation.Status == KeyCredentialStatus.UserCanceled)
                    {
                        // User cancelled the credential
                        throw new TaskCanceledException();
                    }
                }
            }

            if (credentials == null)
            {
                // No Windows Hello, use standard password
                credentials = await ShowPasswordDialogAsync(databaseName);
            }
            return(credentials);
        }
Пример #27
0
        private async Task <bool> CreatePassportKey(string accountId)
        {
            KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync(accountId, KeyCredentialCreationOption.ReplaceExisting);

            if (keyCreationResult.Status == KeyCredentialStatus.Success)
            {
                KeyCredential userKey   = keyCreationResult.Credential;
                IBuffer       publicKey = userKey.RetrievePublicKey();
                KeyCredentialAttestationResult keyAttestationResult = await userKey.GetAttestationAsync();

                IBuffer keyAttestation                    = null;
                IBuffer certificateChain                  = null;
                bool    keyAttestationIncluded            = false;
                bool    keyAttestationCanBeRetrievedLater = false;
                KeyCredentialAttestationStatus keyAttestationRetryType = 0;

                if (keyAttestationResult.Status == KeyCredentialAttestationStatus.Success)
                {
                    keyAttestationIncluded = true;
                    keyAttestation         = keyAttestationResult.AttestationBuffer;
                    certificateChain       = keyAttestationResult.CertificateChainBuffer;
                }
                else if (keyAttestationResult.Status == KeyCredentialAttestationStatus.TemporaryFailure)
                {
                    keyAttestationRetryType           = KeyCredentialAttestationStatus.TemporaryFailure;
                    keyAttestationCanBeRetrievedLater = true;
                }
                else if (keyAttestationResult.Status == KeyCredentialAttestationStatus.NotSupported)
                {
                    keyAttestationRetryType           = KeyCredentialAttestationStatus.NotSupported;
                    keyAttestationCanBeRetrievedLater = false;
                }

                // Package public key, keyAttesation if available,
                // certificate chain for attestation endorsement key if available,
                // status code of key attestation result: keyAttestationIncluded or
                // keyAttestationCanBeRetrievedLater and keyAttestationRetryType
                // and send it to application server to register the user.
                bool serverAddedPassportToAccount = await AddPassportToAccountOnServer();

                if (serverAddedPassportToAccount == true)
                {
                    return(true);
                }
            }
            else if (keyCreationResult.Status == KeyCredentialStatus.UserCanceled)
            {
                // User cancelled the Passport enrollment process
            }
            else if (keyCreationResult.Status == KeyCredentialStatus.NotFound)
            {
                // User needs to create PIN
                //textblock_PassportStatusText.Text = "Microsoft Passport is almost ready!\nPlease go to Windows Settings and set up a PIN to use it.";
                //grid_PassportStatus.Background = new SolidColorBrush(Color.FromArgb(255, 50, 170, 207));
                //button_PassportSignIn.IsEnabled = false;

                m_passportAvailable = false;
            }
            else
            {
            }

            return(false);
        }
Пример #28
0
        public static async Task <bool> CreatePassportKeyAsync()
        {
            var keyCreationResult = await KeyCredentialManager.RequestCreateAsync("temp", KeyCredentialCreationOption.ReplaceExisting);

            return(keyCreationResult.Status == KeyCredentialStatus.Success);
        }