Exemple #1
0
 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);
 }
Exemple #2
0
        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.");
        }
Exemple #3
0
 public void UpdatePasswordByNewKeyMaterial(string newKeymaterial)
 {
     if (!string.IsNullOrEmpty(this.SecretKey))
     {
         this.Password = PasswordFunctions.EncryptPassword(this.SecretKey, newKeymaterial);
     }
 }
Exemple #4
0
        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");
        }
Exemple #5
0
        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");
        }
Exemple #6
0
        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);
        }
Exemple #7
0
        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);
        }
Exemple #8
0
        private bool IsMasterPasswordValid(string masterPassword)
        {
            var isValid = PasswordFunctions.MasterPasswordIsValid(masterPassword, Settings.Instance.MasterPasswordHash);

            if (isValid)
            {
                this.AssignFieldsByOldMasterPassword(masterPassword);
            }
            return(isValid);
        }
Exemple #9
0
        private static string GetKeyMaterial(string password)
        {
            if (string.IsNullOrEmpty(password))
            {
                return(string.Empty);
            }
            String hashToCheck = PasswordFunctions.ComputeMasterPasswordHash(password);

            return(PasswordFunctions.ComputeMasterPasswordHash(password + hashToCheck));
        }
Exemple #10
0
        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);
        }
Exemple #11
0
        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)
            }));
        }
Exemple #12
0
        public static Boolean IsMasterPasswordValid(string passwordToCheck)
        {
            String hashToCheck = PasswordFunctions.ComputeMasterPasswordHash(passwordToCheck);

            if (GetMasterPasswordHash() == hashToCheck)
            {
                UpdateKeyMaterial(passwordToCheck);
                return(true);
            }

            return(false);
        }
Exemple #13
0
        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");
        }
Exemple #14
0
        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}");
            }
        }
Exemple #15
0
        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());
            }
        }
Exemple #16
0
        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();
        }
Exemple #17
0
        private string MigratePassword(string oldPassword)
        {
            var securityPassword = PasswordFunctions.DecryptPassword(oldPassword, this.oldKey);

            return(PasswordFunctions2.EncryptPassword(securityPassword, this.newKey));
        }
Exemple #18
0
 public void UpdatePasswordsByNewKeyMaterial(string newKeyMaterial)
 {
     this.EncryptedKeePassPassword = PasswordFunctions.EncryptPassword(this.KeePassPassword, newKeyMaterial);
     this.EncryptedDefaultPassword = PasswordFunctions.EncryptPassword(this.DefaultPassword, newKeyMaterial);
 }
Exemple #19
0
        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>" +
                                    $"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<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);
        }
Exemple #20
0
 private void AssignFieldsByOldMasterPassword(string masterPassword)
 {
     this.oldKey = PasswordFunctions.CalculateMasterPasswordKey(masterPassword);
     this.storedMasterPassword = PasswordFunctions2.CalculateStoredMasterPasswordKey(masterPassword);
     this.newKey = PasswordFunctions2.CalculateMasterPasswordKey(masterPassword, this.storedMasterPassword);
 }
Exemple #21
0
        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);
        }