public void UpdatePasswordsByNewKeyMaterial(string newKeyMaterial) { this.EncryptedKeePassPassword = PasswordFunctions.EncryptPassword(this.KeePassPassword, newKeyMaterial); this.EncryptedDefaultPassword = PasswordFunctions.EncryptPassword(this.DefaultPassword, newKeyMaterial); this.EncryptedAmazonAccessKey = PasswordFunctions.EncryptPassword(this.AmazonAccessKey, newKeyMaterial); this.EncryptedAmazonSecretKey = PasswordFunctions.EncryptPassword(this.AmazonSecretKey, newKeyMaterial); }
public void V1MasterPasswordIsUniqueTest() { string key1 = PasswordFunctions.CalculateMasterPasswordKey(MASTERPASSWORD); string key2 = PasswordFunctions.CalculateMasterPasswordKey(MASTERPASSWORD); Assert.AreEqual(key1, key2, "generated master password key v1 doesn't equals."); }
public void UpdatePasswordByNewKeyMaterial(string newKeymaterial) { if (!string.IsNullOrEmpty(this.SecretKey)) { this.Password = PasswordFunctions.EncryptPassword(this.SecretKey, newKeymaterial); } }
public void V1PasswordsUniqueEncryptionTest() { string key = PasswordFunctions.CalculateMasterPasswordKey(MASTERPASSWORD); string encryptedPassword = PasswordFunctions.EncryptPassword(USERPASSWORD, key); string encryptedPassword2 = PasswordFunctions.EncryptPassword(USERPASSWORD, key); Assert.AreEqual(encryptedPassword, encryptedPassword2, "password encryption v1 doesn't generate identical encrypted bytes"); }
public void V1PasswordsEncryptDecryptTest() { PasswordsEncryptDecryptCheck(CheckEncryptDecryptPasswordV1); string masterKey = PasswordFunctions.CalculateMasterPasswordKey(MASTERPASSWORD); string decryptedPassword = PasswordFunctions.DecryptPassword(string.Empty, masterKey); Assert.AreEqual(string.Empty, decryptedPassword, "Decryption of empty stored password failed"); }
private static string CheckEncryptDecryptPasswordV1(string password, string masterPassword) { string masterKey = PasswordFunctions.CalculateMasterPasswordKey(masterPassword); string encryptedPassword = PasswordFunctions.EncryptPassword(password, masterKey); string decryptedPassword = PasswordFunctions.DecryptPassword(encryptedPassword, masterKey); Assert.AreEqual(password, decryptedPassword, "Unable to decrypt V1 password"); return(encryptedPassword); }
private static bool TestDatabasePassword(string connectionStringToTest, string databasePassword) { string connectionString = BuildConnectionString(connectionStringToTest); var database = new DataBase(connectionString); string databasePasswordHash = PasswordFunctions.EncryptPassword(databasePassword); bool passwordIsValid = databasePasswordHash == database.GetMasterPasswordHash(); return(passwordIsValid); }
private bool IsMasterPasswordValid(string masterPassword) { var isValid = PasswordFunctions.MasterPasswordIsValid(masterPassword, Settings.Instance.MasterPasswordHash); if (isValid) { this.AssignFieldsByOldMasterPassword(masterPassword); } return(isValid); }
private static string GetKeyMaterial(string password) { if (string.IsNullOrEmpty(password)) { return(string.Empty); } String hashToCheck = PasswordFunctions.ComputeMasterPasswordHash(password); return(PasswordFunctions.ComputeMasterPasswordHash(password + hashToCheck)); }
private static int tryLogin(string email, string password) { renoRatorDBEntities _db = new renoRatorDBEntities(); var user = _db.Users.Where(u => u.email == email).FirstOrDefault(); if (user != null && user.password == PasswordFunctions.CreateHash(password, user.salt)) { return(user.userID); } return(-1); }
private IEnumerable <User> GetUsers() { string content = File.ReadAllText("./users.json"); return(JsonConvert.DeserializeObject <IEnumerable <User> >(content).Select(x => new User() { CreatedOn = DateTime.Now, EmailAddress = x.EmailAddress, Id = x.Id, PasswordHash = PasswordFunctions.GetSHA256(x.PasswordHash) })); }
public static Boolean IsMasterPasswordValid(string passwordToCheck) { String hashToCheck = PasswordFunctions.ComputeMasterPasswordHash(passwordToCheck); if (GetMasterPasswordHash() == hashToCheck) { UpdateKeyMaterial(passwordToCheck); return(true); } return(false); }
public void V1MasterPasswordValidationTest() { // cant use persistence security here, because of initialization depends on newest algorithm string masterHash = PasswordFunctions.ComputeMasterPasswordHash(MASTERPASSWORD); string masterHash2 = PasswordFunctions.ComputeMasterPasswordHash(MASTERPASSWORD); Assert.AreEqual(masterHash, masterHash2); bool isValid = PasswordFunctions.MasterPasswordIsValid(MASTERPASSWORD, masterHash); Assert.IsTrue(isValid, "Couldn't validate stored master password v1"); }
public UserProfile LoginUser(UserProfileLogin userProfileLogin) { bool _isSucess = false; List <DbParameter> _parametros = new List <DbParameter>(); // Definição do parâmetros da consulta: SqlParameter pEmail = new SqlParameter() { ParameterName = "@email", Value = userProfileLogin.EMail }; _parametros.Add(pEmail); // Fim da definição dos parâmetros try { query = @"SELECT P.PessoaId, P.Nome, P.EMail, P.NomeFoto, P.Sexo, P.DtNascimento , P.NrCelular, P.PasswordHash, P.DtCadastro, P.PerfilId, P.Ativo FROM dbo.AD_Pessoa P WHERE P.EMail = @email"; // Define o banco de dados que será usando: CommandSql cmd = new CommandSql(strConnSql, query, EnumDatabaseType.SqlServer, parametros: _parametros); // Obtém os dados do banco de dados: UserProfile userProfile = GetCollection <UserProfile>(cmd)?.FirstOrDefault <UserProfile>(); if (userProfile != null) { _isSucess = PasswordFunctions.ValidaSenha(userProfileLogin.PasswordHash, userProfile.PasswordHash); } if (!_isSucess) { userProfile = null; } return(userProfile); } catch (Exception ex) { throw new Exception($"{ex.Message}"); } }
public async Task <IActionResult> Login([FromForm] LoginModel loginModel, string returnUrl = "/") { if (!ModelState.IsValid) { return(View(loginModel)); } AuthenticatedUser authenticatedUser = null; try { authenticatedUser = _apiFacade.LoginUser(loginModel.EmailAddress, PasswordFunctions.GetSHA256(loginModel.Password)); } catch (Exception ex) { if (!ex.Message.Contains("Unauthorized")) { ModelState.AddModelError("Authenitcation Error", "There was an error logging you in: " + ex.Message); return(View()); } } if (authenticatedUser != null && !string.IsNullOrWhiteSpace(authenticatedUser.JsonToken)) { var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); identity.AddClaim(new Claim(ClaimTypes.Name, loginModel.EmailAddress)); identity.AddClaim(new Claim(ClaimTypes.Sid, authenticatedUser.JsonToken)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, authenticatedUser.Id.ToString())); SetRoles(authenticatedUser, identity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties { IsPersistent = loginModel.RememberMe, ExpiresUtc = DateTime.UtcNow.AddHours(_appSettings.Value.TokenTimeOutInHours) }); return(RedirectToLocal(returnUrl)); } else { ViewBag.Message = "Password or Email address is invalid."; return(View()); } }
public void Save() { var db = new renoRatorDBEntities(); User newUser = new User(); newUser.userTypeID = this.userTypeID; newUser.fname = this.fname; newUser.lname = this.lname; newUser.email = this.email; newUser.password = this.password; if (!String.IsNullOrEmpty(this.bio)) { newUser.bio = this.bio; } if (this.profileGalleryID > 0) { newUser.profileGalleryID = this.profileGalleryID; } if (this.profilePhotoID > 0) { newUser.profilePhotoID = this.profilePhotoID; } if (this.addressID > 0) { newUser.addressID = this.addressID; } if (this.portfolioGalleryID > 0) { newUser.portfolioGalleryID = this.portfolioGalleryID; } // salt and hash the password string salt = PasswordFunctions.CreateSalt(8); newUser.salt = salt; newUser.password = PasswordFunctions.CreateHash(newUser.password, salt); db.AddToUsers(newUser); db.SaveChanges(); }
private string MigratePassword(string oldPassword) { var securityPassword = PasswordFunctions.DecryptPassword(oldPassword, this.oldKey); return(PasswordFunctions2.EncryptPassword(securityPassword, this.newKey)); }
public void UpdatePasswordsByNewKeyMaterial(string newKeyMaterial) { this.EncryptedKeePassPassword = PasswordFunctions.EncryptPassword(this.KeePassPassword, newKeyMaterial); this.EncryptedDefaultPassword = PasswordFunctions.EncryptPassword(this.DefaultPassword, newKeyMaterial); }
public string RessetPasswordById(int id) { bool _sendSucess = false; string _msg = "", _newPassword = "", _newPasswordHash = ""; bool _isBodyHtml = true; string _subject, _textBody; Colaborador _colaborador = new Colaborador(); _colaborador = GetColaboradorById(id); SendEMail _sendMail = new SendEMail(); _newPassword = PasswordFunctions.GetNovaSenhaAcesso(""); _newPasswordHash = PasswordFunctions.CriptografaSenha(_newPassword); using (SqlConnection connection = new SqlConnection(strConnSql)) { connection.Open(); SqlCommand command = connection.CreateCommand(); SqlTransaction transaction; // Start a local transaction. transaction = connection.BeginTransaction("RessetSenhaColaborador"); command.Connection = connection; command.Transaction = transaction; try { // Atualizando a senha na tabela PESSOA: command.CommandText = "" + "UPDATE dbo.AD_Pessoa " + "SET PasswordHash = @PasswordHash " + "WHERE PessoaId = @id"; command.Parameters.AddWithValue("PasswordHash", _newPasswordHash); command.Parameters.AddWithValue("id", _colaborador.PessoaId); int i = command.ExecuteNonQuery(); transaction.Commit(); if (i > 0) { _subject = "Site FBTC - Troca de Senha - A sua nova senha de acesso chegou!"; _textBody = "<html><body> " + $"<p>Olá {_colaborador.Nome}!</p>" + "<p>Esta mensagem foi gerada pelo sistema Troca de Senha do Site FBTC.</p>" + "<p>Conforme solicitação através do site, a sua senha de acesso a sua conta no site fbtc.org.br foi reiniciada.</br></br>" + "Para você logar-se, por favor, informe o seu e-mail e a senha abaixo:</br></br></br>" + $" <b>{_newPassword}</b></br></br></br>" + "Por favor, para seu segurança, troque-a no seu próximo acesso.</br></br></br>" + "<a href='http://administrativo.fbtc.org.br' target='_blank'>http://administrativo.fbtc.org.br - Acessar sua Conta</a></br>" + "</p>" + "<p><i>2018 - FBTC Federação Brasileira de Terapias Cognitivas - Direitos reservados.</i></p> " + "<p>Este é um e-mail automático da FBTC, por favor não o responda.</p> " + "</body></html> "; _sendSucess = _sendMail.SendMessage(_colaborador.EMail, _subject, _isBodyHtml, _textBody); _msg = _sendSucess == true ? $"A nova senha foi enviada para o e-mail: { _colaborador.EMail }." : "Houve uma falha no envio da sua senha"; } else { _msg = "Atualização NÃO Realizada com sucesso"; _sendSucess = false; } } catch (Exception ex) { if (ex.Message.IndexOf("Mail") < 0) { try { transaction.Rollback(); } catch (Exception ex2) { throw new Exception($"Rollback Exception Type:{ex2.GetType()}. Erro:{ex2.Message}"); } } if (ex.Message.IndexOf("System.Net.Mail.SmtpException") > 0) { return("ATENÇÃO: Não foi possível enviar o e-mail com a nova senha agora. Por favor, tente novamente mais tarde."); } else { throw new Exception($"Commit Exception Type:{ex.GetType()}. Erro:{ex.Message}"); } } finally { connection.Close(); } } return(_msg); }
private void AssignFieldsByOldMasterPassword(string masterPassword) { this.oldKey = PasswordFunctions.CalculateMasterPasswordKey(masterPassword); this.storedMasterPassword = PasswordFunctions2.CalculateStoredMasterPasswordKey(masterPassword); this.newKey = PasswordFunctions2.CalculateMasterPasswordKey(masterPassword, this.storedMasterPassword); }
public string Save(UserProfile userProfile) { bool _resultado = false; string _msg = ""; using (SqlConnection connection = new SqlConnection(strConnSql)) { string _passWord = ""; string _passwordHash = ""; if (!string.IsNullOrEmpty(userProfile.PasswordHashReturned)) { _passwordHash = PasswordFunctions.CriptografaSenha(userProfile.PasswordHashReturned); _passWord = "******"; } connection.Open(); SqlCommand command = connection.CreateCommand(); SqlTransaction transaction; // Start a local transaction. transaction = connection.BeginTransaction("AtualizarUserProfile"); command.Connection = connection; command.Transaction = transaction; try { // Atualizando os dados na tabela PESSOA: string _dtNasc = userProfile.DtNascimento != null ? ", DtNascimento = @DtNascimento " : ""; command.CommandText = $@" UPDATE dbo.AD_Pessoa SET Nome = @nome, EMail = @EMail, NomeFoto = @NomeFoto, Sexo = @Sexo, NrCelular = @NrCelular, PerfilId = @PerfilId {_dtNasc} {_passWord} WHERE PessoaId = @id"; command.Parameters.AddWithValue("Nome", userProfile.Nome); command.Parameters.AddWithValue("EMail", userProfile.EMail); command.Parameters.AddWithValue("NomeFoto", userProfile.NomeFoto); command.Parameters.AddWithValue("Sexo", userProfile.Sexo); command.Parameters.AddWithValue("NrCelular", userProfile.NrCelular); command.Parameters.AddWithValue("PerfilId", userProfile.PerfilId); command.Parameters.AddWithValue("id", userProfile.PessoaId); if (_dtNasc != "") { command.Parameters.AddWithValue("DtNascimento", userProfile.DtNascimento); } if (!string.IsNullOrEmpty(userProfile.PasswordHashReturned)) { command.Parameters.AddWithValue("PassWordHash", _passwordHash); } int i = command.ExecuteNonQuery(); _resultado = i > 0; _msg = i > 0 ? "Atualização realizada com sucesso" : "Atualização NÃO realizada com sucesso"; transaction.Commit(); } catch (Exception ex) { try { transaction.Rollback(); } catch (Exception ex2) { throw new Exception($"Rollback Exception Type:{ex2.GetType()}. Erro:{ex2.Message}"); } throw new Exception($"Commit Exception Type:{ex.GetType()}. Erro:{ex.Message}"); } finally { connection.Close(); } } return(_msg); }