private void PopulatePasswordList() { // Initialize password list cbxPasswordList.Items.Clear(); try { // Load vault PasswordVault vault = new PasswordVault(); // Get all password names from vault and add to dropdown list foreach (var name in vault.GetPasswordNames()) { cbxPasswordList.Items.Add(name); } } catch (Exception ex) { // Error loading vault MessageBox.Show(ex.Message, CAP_ERROR); } }
public async Task <ByteTuple> DecryptAsync(string publicKey) { var vault = new PasswordVault(); var credential = vault.Retrieve($"{_session}", publicKey); var split = credential.Password.Split(';'); var saltString = split[0]; var dataString = split[1]; var localPasswordString = split[2]; var typeString = split[3]; var salt = CryptographicBuffer.DecodeFromHexString(saltString); var data = CryptographicBuffer.DecodeFromHexString(dataString); var localPassword = CryptographicBuffer.DecodeFromHexString(localPasswordString); var dialog = new SettingsPasscodeConfirmPopup(passcode => Task.FromResult(false), true); var confirm = await dialog.ShowQueuedAsync(); if (confirm != ContentDialogResult.Primary) { return(null); } var secret = CryptographicBuffer.ConvertStringToBinary(dialog.Passcode, BinaryStringEncoding.Utf8); var material = PBKDF2(secret, salt); var objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7); var key = objAlg.CreateSymmetricKey(material); var decrypt = CryptographicEngine.Decrypt(key, data, null); CryptographicBuffer.CopyToByteArray(decrypt, out byte[] result); CryptographicBuffer.CopyToByteArray(localPassword, out byte[] local); return(new ByteTuple(result, local)); }
private static string GetToken(string kind) { var vault = new PasswordVault(); try { var credential = vault.FindAllByResource(RESOURCE_NAME).FirstOrDefault(); if (credential != null) { return(vault.Retrieve(RESOURCE_NAME, kind).Password); } else { return(null); } } catch (Exception e) { return(null); } }
/// <summary> /// Retrieves the CompositeKey information from the Password vault. /// </summary> /// <param name="dbPath">Database Path. This is the identification of the database, if database is moved or name is changed, /// New credentials must be created.</param> /// <param name="rResult">KeyCredential object used to sign a key to decrypt the compositekey information.</param> /// <returns>KeyList object with all the information to compose the CompositeKey.</returns> internal async static Task <KeyList> RetrieveKeys(string dbPath, KeyCredentialRetrievalResult rResult) { PasswordVault myVault = new PasswordVault(); var newCredential = new PasswordCredential(); try { newCredential = myVault.Retrieve(dbPath, WinHelloUnlockExt.ProductName); newCredential.RetrievePassword(); } catch (Exception ev) { MessageService.ShowInfo("Not able to retrieve Composite Key from Microsoft Password Vault. " + "Maybe saving again will solve the problem. Message: " + ev.Message); return(new KeyList(null, null)); } try { string encrypted = newCredential.Password; ProtectedString decrypted = await Decrypt(encrypted, rResult); if (decrypted != null) { KeyList Keys = Library.ConvertKeyList(decrypted); decrypted = ProtectedString.EmptyEx; return(Keys); } else { return(new KeyList(null, null)); } } catch (Exception ev) { MessageService.ShowInfo("Credential not retrieved: " + ev.Message); Debug.Write(ev.Message); return(new KeyList(null, null)); } }
public UserInfo GetUserInfo(bool retrievePassword = false) { this.logger.Debug("GetUserInfo"); PasswordVault vault = new PasswordVault(); try { var list = vault.FindAllByResource(GoogleAccountsResource); if (list.Count > 0) { this.logger.Debug("GetUserInfo: Found password credentials. Count: {0}", list.Count); if (retrievePassword) { this.logger.Debug("GetUserInfo: Retrieving password."); list[0].RetrievePassword(); } return(new UserInfo(list[0].UserName, list[0].Password) { RememberAccount = true }); } } catch (Exception exception) { if (((uint)exception.HResult) != 0x80070490) { this.logger.Error(exception, "Exception while tried to GetUserInfo."); } else { this.logger.Debug("GetUserInfo: Not found."); } } this.logger.Debug("Password credentials could not find."); return(null); }
public async void deleteItem(string key, JObject options, IPromise promise) { if (string.IsNullOrEmpty(key)) { promise.Reject(new ArgumentNullException("KEY IS REQUIRED")); return; } try { string name = sharedPreferences(options); var vault = new PasswordVault(); var credential = vault.Retrieve(name, key); vault.Remove(credential); promise.Resolve(key); } catch (Exception ex) { promise.Reject("ERROR DELETE : " + ex.Message); } }
public PasswordCredential GetSavedCredentials(string resource) { try { var vault = new PasswordVault(); var credentials = vault.FindAllByResource(resource); var cred = credentials.FirstOrDefault(); if (cred != null) { return(vault.Retrieve(resource, cred.UserName)); } else { return(null); } } // The password vault throws System.Exception if no credentials have been stored with this resource. catch (Exception) { return(null); } }
private Tuple <string, string> GetTokenFromVault(string resName) { string userName = string.Empty; string password = string.Empty; var vault = new PasswordVault(); try { var credential = vault.FindAllByResource(resName).FirstOrDefault(); if (credential?.Properties != null) { userName = credential.UserName; password = vault.Retrieve(resName, userName).Password; } } catch (Exception) { Debug.WriteLine($"Could not find resorce {resName} in vault"); } return(new Tuple <string, string>(userName, password)); }
private static PasswordCredential GetCredentialFromLocker() { PasswordCredential credential = null; var vault = new PasswordVault(); var credentialList = vault.RetrieveAll(); if (credentialList.Count > 0) { if (credentialList.Count == 1) { credential = credentialList[0]; } else { credential = vault.RetrieveAll().FirstOrDefault(); } credential.RetrievePassword(); } return(credential); }
private void Delete_Click(object sender, RoutedEventArgs e) { if (InputResourceValue.Text == "" || InputUserNameValue.Text == "") { rootPage.NotifyUser("Inputs are missing. Resource and Username are required.", NotifyType.ErrorMessage); } else { try { // This is the code to remove a credentialt from PasswordVault by supplying resource or username PasswordVault vault = new PasswordVault(); PasswordCredential cred = vault.Retrieve(InputResourceValue.Text, InputUserNameValue.Text); vault.Remove(cred); rootPage.NotifyUser("Credential removed successfully. Resource: " + InputResourceValue.Text + " Username: "******".", NotifyType.StatusMessage); } catch (Exception Error) // No stored credentials, so none to delete { rootPage.NotifyUser(Error.Message, NotifyType.ErrorMessage); } } }
public void Logout() { string provider = MobileServiceAuthenticationProvider.MicrosoftAccount.ToString(); // Use the PasswordVault to securely store and access credentials. PasswordVault vault = new PasswordVault(); PasswordCredential credential = null; try { // Try to get an existing credential from the vault. credential = vault.FindAllByResource(provider).FirstOrDefault(); } catch { //nothing to do } if (credential != null) { vault.Remove(credential); } }
private static void ClearStoredCredentials(PasswordVault vault) { if (vault == null) { throw new ArgumentNullException("vault"); } try { var credentials = vault.FindAllByResource(App.WinRTByExampleBookClient.ApplicationUri.DnsSafeHost); if (credentials != null) { foreach (var credential in credentials) { vault.Remove(credential); } } } catch (Exception) { // The PasswordVault API throws a general Exception if a resource store is not found. } }
/// <summary> /// Disconnects a soundbyte service /// </summary> public void DisconnectService(ServiceType serviceType) { // Get the password vault var vault = new PasswordVault(); switch (serviceType) { case ServiceType.SoundCloud: // Remove the token _soundCloudToken = null; // Remove everything in the vault vault.FindAllByResource("SoundByte.SoundCloud").ToList().ForEach(x => vault.Remove(x)); break; case ServiceType.Fanburst: // Remove the token _fanburstToken = null; // Remove everything in the vault vault.FindAllByResource("SoundByte.FanBurst").ToList().ForEach(x => vault.Remove(x)); break; } }
public bool TryGetPassword(string username, out string password) { vault = new Windows.Security.Credentials.PasswordVault(); try { IReadOnlyList <PasswordCredential> creds = vault.FindAllByUserName(username); foreach (var cred in creds) { if (cred.UserName == username) { cred.RetrievePassword(); password = cred.Password; return(true); } } } catch (Exception e) { } password = null; return(false); }
//public async Task<MobileServiceUser> CustomLogin(string username, string password) //{ // string message; // MobileServiceUser user = null; // // Use the PasswordVault to securely store and access credentials. // PasswordVault vault = new PasswordVault(); // PasswordCredential credential = null; // try // { // // get the token // //var token = await GetAuthenticationToken(username, password); // //// authenticate: create and use a mobile service user // //user = new MobileServiceUser(token.Guid); // //user.MobileServiceAuthenticationToken = token.Access_Token; // //// Create and store the user credentials. // //credential = new PasswordCredential("custom", // // user.UserId, user.MobileServiceAuthenticationToken); // //vault.Add(credential); // //App.MobileService.CurrentUser = user; // } // catch (MobileServiceInvalidOperationException) // { // message = "You must log in. Login Required"; // await HelpersClass.ShowDialogAsync(message); // } // return user; //} //public async Task<AuthenticationToken> //GetAuthenticationToken(string username, string email, string password) //{ // try // { // //using (var pc = new PrincipalContext(ContextType.Domain)) // //{ // // using (var up = new UserPrincipal(pc)) // // { // // up.SamAccountName = username; // // up.EmailAddress = email; // // up.SetPassword(password); // // up.Enabled = true; // // up.ExpirePasswordNow(); // // up.Save(); // // } // //} // } // catch (MobileServiceInvalidOperationException exception) // { // //if (string.Equals(exception.Message, "invalid_grant")) // // throw new InvalidGrantException("Wrong credentails", // // exception); // //else // // throw; // } // return null; //} public async Task <MobileServiceUser> Login(MobileServiceAuthenticationProvider provider) { string message; MobileServiceUser user = null; // This sample uses the Facebook provider. // Use the PasswordVault to securely store and access credentials. PasswordVault vault = new PasswordVault(); PasswordCredential credential = null; try { // Login with the identity provider. user = await App.MobileService .LoginAsync(provider); // Create and store the user credentials. credential = new PasswordCredential(provider.ToString(), user.UserId, user.MobileServiceAuthenticationToken); JObject obj = new JObject(); obj.Add("Id", user.UserId); obj.Add("Name", credential.UserName); vault.Add(credential); string response = await CallAPI(@"/api/Users", HTTPMETHOD.POST, obj); message = string.Format("You are now logged in - {0}", user.UserId); } catch (MobileServiceInvalidOperationException) { message = "You must log in. Login Required"; await HelpersClass.ShowDialogAsync(message); } catch { } return(user); }
/// <summary> /// 构造函数。 /// </summary> /// <param name="rootNavigationService">根导航服务。</param> public IdentityService(IRootNavigationService rootNavigationService) { _rootNavigationService = rootNavigationService; var passwordVault = new PasswordVault(); PasswordCredential refreshTokenCredential = null; try { refreshTokenCredential = passwordVault.Retrieve(RefreshTokenResource, DefaultUsername); } catch { // ignored } if (refreshTokenCredential != null) { refreshTokenCredential.RetrievePassword(); _refreshToken = refreshTokenCredential.Password; } PasswordCredential accessTokenCredential = null; try { accessTokenCredential = passwordVault.Retrieve(AccessTokenResource, DefaultUsername); } catch { // ignored } if (accessTokenCredential != null) { accessTokenCredential.RetrievePassword(); _accessToken = accessTokenCredential.Password; } }
public async Task SignOutAsync() { PortalService.CurrentPortalService.SignOut(); try { if (!App.IsOrgOAuth2) { // remove credentials from vault var vault = new PasswordVault(); PasswordCredential cred = vault.FindAllByResource(App.OrganizationUrl) != null?vault.FindAllByResource(App.OrganizationUrl).FirstOrDefault() : null; if (cred != null) { vault.Remove(cred); } } } catch (Exception ex) { var _ = App.ShowExceptionDialog(ex); } ResetSignInProperties(); // if anonymous access is enabled go back to the main page otherwise go back to the signin page bool isAnonymousAccess = await GetAnonymousAccessStatusAsync(); if (isAnonymousAccess) { (new NavigationService()).Navigate(App.MainPageName); await SignInAnonymouslyAsync(); } else { (new NavigationService()).Navigate(App.BlankPageName); } }
public async Task <User> RestoreSignInStatus() { // Use the PasswordVault to securely store and access credentials. var vault = new PasswordVault(); // Try to get an existing credential from the vault. var credential = vault.RetrieveAll().FirstOrDefault(); if (credential != null) { // Create a user from the stored credentials. var user = new MobileServiceUser(credential.UserName); credential.RetrievePassword(); user.MobileServiceAuthenticationToken = credential.Password; // Set the user from the stored credentials. AzureAppService.Current.CurrentUser = user; try { var userContract = await AzureAppService.Current.InvokeApiAsync <UserContract>("User", HttpMethod.Get, null); return(userContract.ToDataModel()); } catch (MobileServiceInvalidOperationException invalidOperationException) { if (invalidOperationException.Response.StatusCode == HttpStatusCode.Unauthorized) { // Remove the credentials. ResetPasswordVault(); AzureAppService.Current.CurrentUser = null; credential = null; } } } return(null); }
public async Task Login() { try { var vault = new PasswordVault(); vault.RetrieveAll(); var resources = vault.FindAllByResource(PyxisConstants.ApplicationKey); var credential = resources.FirstOrDefault(); if (credential == null) { return; } credential.RetrievePassword(); var account = await _pixivClient.Authorization .Login(get_secure_url => 1, grant_type => "password", client_secret => "HP3RmkgAmEGro0gn1x9ioawQE8WMfvLXDz3ZqxpK", device_token => Guid.NewGuid().ToString().Replace("-", ""), password => credential.Password, client_id => "bYGKuGVw91e0NMfPGp44euvGt59s", username => credential.UserName); if (account == null) { Clear(); return; } IsLoggedIn = true; IsPremium = account.User.IsPremium; LoggedInAccount = account.User; } catch (Exception e) { Debug.WriteLine(e.Message); } }
private IEnumerable <MusicEndpoint> SaveCredentials(IEnumerable <MusicEndpoint> data) { var ret = new List <MusicEndpoint>(); var vault = new PasswordVault(); foreach (var e in data) { if (e.Name != string.Empty && e.Username != string.Empty && e.Password != string.Empty) { vault.Add(new PasswordCredential(CredPrefix + e.Name, e.Username, e.Password)); ret.Add(new MusicEndpoint() { Name = e.Name, Server = e.Server, Port = e.Port, CloudServerID = e.CloudServerID, EndpointType = e.EndpointType, Protocol = e.Protocol }); } } return(ret); }
private void ClearAllPasswordCredentials(PasswordVault vault) { try { var all = vault.FindAllByResource(LastFmSessionResource); foreach (var credential in all) { this.logger.Debug("SaveCurrentSessionAsync: Remove old sessions."); vault.Remove(credential); } } catch (Exception exception) { if (((uint)exception.HResult) != 0x80070490) { this.logger.Error(exception, "Exception while tried to ClearAllPasswordCredentials."); } else { this.logger.Debug("ClearAllPasswordCredentials: Not found."); } } }
private void LoadSettings() { var vault = new PasswordVault(); try { var credentialList = vault.FindAllByResource(ResourceName); inputUser.Text = credentialList[0].UserName; credentialList[0].RetrievePassword(); inputPassword.Password = credentialList[0].Password; ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; splunkHost.Text = localSettings.Values["host"].ToString(); inputPort.Text = localSettings.Values["port"].ToString(); if (string.Equals(localSettings.Values["scheme"].ToString(), "Http", StringComparison.OrdinalIgnoreCase)) { Http.IsChecked = true; } } catch { } }
public void RemoveResource(string resource) { PasswordVault vault = new PasswordVault(); PasswordCredential credential = null; try { // Try to get an existing credential from the vault. credential = vault.FindAllByResource(resource) .FirstOrDefault(); } catch (Exception ex) { // When there is no matching resource an error occurs, which we ignore. Debug.WriteLine(ex.ToString()); } if (credential != null) { vault.Remove(credential); } }
/// <summary> /// Removes all AWS Credentials associated with this settings file /// </summary> public static void RemoveAwsSiteCredentials() { var vault = new PasswordVault(); IReadOnlyList <PasswordCredential> possibleCredentials; try { possibleCredentials = vault.FindAllByResource(AwsSiteCredentialResourceString()); } catch (Exception) { //Nothing to remove return; } if (possibleCredentials == null || !possibleCredentials.Any()) { return; } possibleCredentials.ToList().ForEach(x => vault.Remove(x)); }
public bool Save(string URL, string userName, string password) { if (!string.IsNullOrWhiteSpace(URL) && !string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password)) { var vault = new PasswordVault(); ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; try { vault.Add(new PasswordCredential(AppConfig.AppName, userName, password)); localSettings.Values["URL"] = URL; } catch (System.Exception) { return(false); } return(true); } else { return(false); } }
public AdnOAuthConnector( string baseUrl, string consumerKey, string consumerSecret) { _client = new RestClient(baseUrl); ConsumerKey = consumerKey; ConsumerSecret = consumerSecret; _vault = new PasswordVault(); _vault.Add(new PasswordCredential( "AdnOAuthConnector", "AccessToken", "-")); _vault.Add(new PasswordCredential( "AdnOAuthConnector", "AccessTokenSecret", "-")); }
public static PasswordCredential GetCredentialFromLocker() { PasswordCredential credential = null; var vault = new PasswordVault(); try { var credentialList = vault.FindAllByResource("bauk"); if (credentialList.Count > 0) { credential = credentialList[0]; return(credential); } } catch (Exception) { return(null); } return(null); }
private static PasswordCredential GetCredentialFromLocker() { PasswordCredential credential = null; var vault = new PasswordVault(); try { var credentials = vault.FindAllByResource(API_KEY); if (credentials.Count > 0) { credential = credentials[0]; credential.RetrievePassword(); } } catch (Exception) { // No credentials found } return(credential); }
public ObservableCollection <ConnectionModel> GetAllConnectionsFromStorage() { var vault = new PasswordVault(); var connectionList = new ObservableCollection <ConnectionModel>(); try { var connectionListFromStorage = vault.FindAllByResource(VAULT_NAME); foreach (var connection in connectionListFromStorage) { connection.RetrievePassword(); connectionList.Add(new ConnectionModel { ConnectionName = connection.UserName, NewConnectionName = connection.UserName, ConnectionString = connection.Password, NewConnectionString = connection.Password }); } } catch { } return(connectionList); }
private async Task TwitterPoster() { SosPageText += "\n Checking credentials... \n"; RaisePropertyChanged(() => SosPageText); var vault = new PasswordVault(); try { var credentialList = vault.FindAllByUserName("TwitterAccessToken"); if (credentialList.Count <= 0) { SosPageText += "Twitter not configured \n"; return; } var twitteraccesstoken = vault.Retrieve("Friend", "TwitterAccessToken"); var twitteraccesstokensecret = vault.Retrieve("Friend", "TwitterAccessTokenSecret"); SosPageText += "Credentials Retrieved \n"; // Set up your credentials (https://apps.twitter.com) //Use your own consumerKey and consumerSecret below! await AuthTokens.KeyRetriever(); Auth.SetUserCredentials(AuthTokens.TwitterConsumerKey, AuthTokens.TwitterConsumerSecret, twitteraccesstoken.Password, twitteraccesstokensecret.Password); Tweet.PublishTweet(Message + " \n" + _latitude + "\n" + _longitude); SosPageText += "Publishing Tweet... \n"; } catch (Exception e) { SosPageText += "Twitter not configured \n"; Debug.WriteLine(e); } RaisePropertyChanged(() => SosPageText); }