Exemple #1
0
        public ActionResult Register(string email, string password, string password2)
        {
            if (!IsEmailAddress(email))
            {
                return(View(new RegisterVM
                {
                    ErrorMessage = "You must enter a valid email address"
                }));
            }

            if (email.IsNullOrEmpty() || password.IsNullOrEmpty() || password2.IsNullOrEmpty())
            {
                return(View(new RegisterVM
                {
                    ErrorMessage = "All fields marked with * are mandatory"
                }));
            }

            if (password != password2)
            {
                return(View(new RegisterVM
                {
                    ErrorMessage = "Passwords do not match"
                }));
            }

            if (!PasswordMeetsPolicy(password, PwdPolicy))
            {
                return(View(new RegisterVM
                {
                    ErrorMessage = "Password must be at least 6 characters long"
                }));
            }

            var user = userService.GetUser(email);

            if (user != null)
            {
                return(View(new RegisterVM
                {
                    ErrorMessage = "That email is already taken"
                }));
            }

            var salt = PWDTK.GetRandomSalt(saltSize);
            var hash = PWDTK.PasswordToHash(salt, password, Configuration.GetHashIterations());

            user = new User
            {
                UserName      = email,
                Salt          = salt,
                Password      = hash,
                LoginProvider = LoginProvider.Internal
            };

            user.Id = userService.InsertUser(user, () => Redis.AddUser(user));
            FormsAuthentication.SetAuthCookie(user.Id.ToString(), createPersistentCookie: true);

            return(RedirectToAction("Index", "Home"));
        }
Exemple #2
0
        private void CmdGuardar_Click()
        {
            try
            {
                //  tblUser tbluser = _db.tblUsers.Find(_Id);
                // _db.Entry(tbluser).State = System.Data.Entity.EntityState.Modified;

                IntPtr passwordBSTR     = default(IntPtr);
                string insecurePassword = "";
                passwordBSTR     = Marshal.SecureStringToBSTR(Password);
                insecurePassword = Marshal.PtrToStringBSTR(passwordBSTR);

                IntPtr passwordVerificationBSTR     = default(IntPtr);
                string insecurePasswordVerification = string.Empty;

                passwordVerificationBSTR     = Marshal.SecureStringToBSTR(PasswordVerification);
                insecurePasswordVerification = Marshal.PtrToStringBSTR(passwordVerificationBSTR);

                if (!insecurePassword.Equals(insecurePasswordVerification))
                {
                    throw new Exception("Error con el Password");
                }

                //Hash password
                if (!PasswordMeetsPolicy(insecurePassword, PwdPolicy))
                {
                    return;
                }

                _salt = PWDTK.GetRandomSalt(saltSize);

                string salt = PWDTK.GetSaltHexString(_salt);

                _hash = PWDTK.PasswordToHash(_salt, insecurePassword, iterations);

                var hashedPassword = PWDTK.HashBytesToHexString(_hash);

                using (SqlExcuteCommand exe = new SqlExcuteCommand()
                {
                    DBCnnStr = DBEndososCnnStr
                })
                {
                    exe.MyUpdateUser(_Id, hashedPassword, salt);
                }

                //  tbluser.SecurityStamp = salt;
                //  tbluser.PasswordHash = hashedPassword;

                //_db.SaveChanges();
                MessageBox.Show("Dones...", "Done", MessageBoxButton.OK, MessageBoxImage.Information);
                CmdSalir_Click();
            }
            catch (Exception ex)
            {
                MethodBase site = ex.TargetSite;
                MessageBox.Show(ex.Message, site.Name, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #3
0
        public bool HashGeneratedPassword(string password)
        {
            try
            {
                Salt = PWDTK.GetRandomSalt(saltSize);
                Hash = PWDTK.PasswordToHash(Salt, password, iterations);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemple #4
0
        public bool HashPassword(string password)
        {
            //A check to make sure the supplied password meets our defined password
            //policy before using CPU resources to calculate hash, this step is optional
            if (PasswordMeetsPolicy(password, PwdPolicy))
            {
                //Get a random salt
                Salt = PWDTK.GetRandomSalt(saltSize);
                //Generate the hash value
                Hash = PWDTK.PasswordToHash(Salt, password, iterations);

                return(true);
            }
            return(false);
        }
Exemple #5
0
        private void GetHashButton_Click(object sender, RoutedEventArgs e)
        {
            if (!PasswordMeetsPolicy(PasswordTextBox.Password, PwdPolicy))
            {
                return;
            }

            //Get a random salt
            _salt = PWDTK.GetRandomSalt(saltSize);
            //Generate the hash value
            _hash = PWDTK.PasswordToHash(_salt, PasswordTextBox.Password, iterations);
            //store as a minimum salt, hash and the userID in the database now, I would also recomend storing iteration count as this will likely change in the future as hardware computes faster and so you may need to adjust iterations in the future
            CompareHashButton.IsEnabled = true;
            MessageBox.Show("Users Password Hash: " + PWDTK.HashBytesToHexString(_hash));
            MessageBox.Show("Hash stored, now try changing the text in the password field and hit the \"Compare\" button");
        }
Exemple #6
0
        public ActionResult ResetPassword(string guid, string password, string passwordConfirmed)
        {
            if (password.IsNullOrEmpty() || passwordConfirmed.IsNullOrEmpty())
            {
                TempData["message"] = "Password can not be empty";
                return(View());
            }

            if (password != passwordConfirmed)
            {
                TempData["message"] = "Passwords must match";
                return(View());
            }

            if (!PasswordMeetsPolicy(password, PwdPolicy))
            {
                TempData["message"] = "Password must be at least 6 characters long";
                return(View());
            }

            var user = userService.GetUserByGuid(guid);

            if (user == null)
            {
                TempData["message"] = "We couldn't find that user!";
                return(View());
            }

            var salt = PWDTK.GetRandomSalt(saltSize);
            var hash = PWDTK.PasswordToHash(salt, password, Configuration.GetHashIterations());

            userService.UpdateUserPassword(user.Id, salt, hash);

            TempData["message"] = "ok";
            return(View());
        }
Exemple #7
0
        private void Guardar_Click()
        {
            try
            {
                string areasDeAcceso = string.Empty;

                foreach (string s in _AreasDeAcceso)
                {
                    areasDeAcceso += s;
                }
                switch (_Operation)
                {
                case 1:
                {        //Anadir
                    IntPtr passwordBSTR     = default(IntPtr);
                    string insecurePassword = "";
                    passwordBSTR     = Marshal.SecureStringToBSTR(Password);
                    insecurePassword = Marshal.PtrToStringBSTR(passwordBSTR);

                    IntPtr passwordVerificationBSTR     = default(IntPtr);
                    string insecurePasswordVerification = string.Empty;

                    passwordVerificationBSTR     = Marshal.SecureStringToBSTR(PasswordVerification);
                    insecurePasswordVerification = Marshal.PtrToStringBSTR(passwordVerificationBSTR);

                    if (!insecurePassword.Equals(insecurePasswordVerification))
                    {
                        throw new Exception("Error con el Password");
                    }

                    //Policy
                    if (!userMeetsPolicy(CbUser_Text, UserPolicy))
                    {
                        return;
                    }

                    if (!PasswordMeetsPolicy(insecurePassword, PwdPolicy))
                    {
                        return;
                    }

                    //Hash password
                    _salt = PWDTK.GetRandomSalt(saltSize);

                    string salt = PWDTK.GetSaltHexString(_salt);

                    _hash = PWDTK.PasswordToHash(_salt, insecurePassword, iterations);

                    var hashedPassword = PWDTK.HashBytesToHexString(_hash);

                    List <tblUser> u = new List <tblUser>
                    {
                        new tblUser
                        {
                            UserId        = System.Guid.NewGuid(),
                            UserName      = CbUser_Text,
                            PasswordHash  = hashedPassword,
                            SecurityStamp = salt,
                            Email         = CbUser_Text + "@jolpr.com",
                            AreasDeAcceso = areasDeAcceso
                        }
                    };

                    using (SqlExcuteCommand exe = new SqlExcuteCommand()
                        {
                            DBCnnStr = DBEndososCnnStr
                        })
                    {
                        exe.MyInsertUsers(u[0].UserId, u[0].UserName, u[0].PasswordHash, u[0].SecurityStamp, u[0].Email, u[0].AreasDeAcceso);
                    }

                    MyRefresh();
                    //   u.ForEach(m => _db.tblUsers.Add(m));
                    //  _db.SaveChanges();
                }
                break;

                case 2:    //Editar Areas De Acceso
                {
                    using (SqlExcuteCommand exe = new SqlExcuteCommand()
                        {
                            DBCnnStr = DBEndososCnnStr
                        })
                    {
                        exe.MyUpdateUser(_Id, areasDeAcceso);
                    }

                    MyRefresh();


                    // tblUser tbluser = _db.tblUsers.Find(_Id);
                    // _db.Entry(tbluser).State = System.Data.Entity.EntityState.Modified;
                    //
                    // tbluser.AreasDeAcceso = areasDeAcceso;
                    //
                    // _db.SaveChanges();
                }
                break;

                case 3:    //Delete
                {
                    string msg = "You are about to delete 1 user\r";
                    msg += "Click yes to permanently delete this user( " + CbUser_Text + " ).\r";
                    msg += "You won't be able to undo those changes.";

                    var response = MessageBox.Show("!!!" + msg, "Delete...", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);

                    if (response == MessageBoxResult.Yes)
                    {
                        using (SqlExcuteCommand exe = new SqlExcuteCommand()
                            {
                                DBCnnStr = DBEndososCnnStr
                            })
                        {
                            exe.MyDeleteUsers(_Id);
                        }

                        MyRefresh();

                        //Users tbluser = _db.tblUsers.Find(_Id);
                        //
                        //
                        //_db.tblUsers.Remove(tbluser);
                        //_db.SaveChanges();
                    }
                }
                break;

                case 4:     //Edit Pass
                {
                    //    tblUser tbluser = _db.tblUsers.Find(_Id);
                    //    _db.Entry(tbluser).State = System.Data.Entity.EntityState.Modified;
                    //
                    IntPtr passwordBSTR     = default(IntPtr);
                    string insecurePassword = "";
                    passwordBSTR     = Marshal.SecureStringToBSTR(Password);
                    insecurePassword = Marshal.PtrToStringBSTR(passwordBSTR);

                    IntPtr passwordVerificationBSTR     = default(IntPtr);
                    string insecurePasswordVerification = string.Empty;

                    passwordVerificationBSTR     = Marshal.SecureStringToBSTR(PasswordVerification);
                    insecurePasswordVerification = Marshal.PtrToStringBSTR(passwordVerificationBSTR);

                    if (!insecurePassword.Equals(insecurePasswordVerification))
                    {
                        throw new Exception("Error con el Password");
                    }

                    //Policy
                    if (!userMeetsPolicy(CbUser_Text, UserPolicy))
                    {
                        return;
                    }

                    if (!PasswordMeetsPolicy(insecurePassword, PwdPolicy))
                    {
                        return;
                    }

                    //Hash password
                    _salt = PWDTK.GetRandomSalt(saltSize);

                    string salt = PWDTK.GetSaltHexString(_salt);

                    _hash = PWDTK.PasswordToHash(_salt, insecurePassword, iterations);

                    var hashedPassword = PWDTK.HashBytesToHexString(_hash);


                    using (SqlExcuteCommand exe = new SqlExcuteCommand()
                        {
                            DBCnnStr = DBEndososCnnStr
                        })
                    {
                        exe.MyUpdateUser(_Id, hashedPassword, salt);
                    }

                    MyRefresh();


                    //    tbluser.SecurityStamp = salt;
                    //    tbluser.PasswordHash = hashedPassword;
                    //
                    //    _db.SaveChanges();
                }
                break;
                }
                Cancelar_Click();
            }
            catch (Exception ex)
            {
                MethodBase site = ex.TargetSite;
                MessageBox.Show(ex.ToString(), site.Name, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #8
0
        /*
         * protected void btnLogin_Click(object sender, EventArgs e) {
         *  if (Membership.ValidateUser(tbUserName.Text, tbPassword.Text)) {
         *      if(string.IsNullOrEmpty(Request.QueryString["ReturnUrl"])) {
         *          FormsAuthentication.SetAuthCookie(tbUserName.Text, false);
         *          Response.Redirect("~/");
         *      }
         *      else
         *          FormsAuthentication.RedirectFromLoginPage(tbUserName.Text, false);
         *  }
         *  else {
         *      tbUserName.ErrorText = "Invalid user";
         *      tbUserName.IsValid = false;
         *  }
         * }
         */


        protected void ASPxButtonLogin_Click(object sender, EventArgs e)
        {
            Page.Validate();

            if (!Page.IsValid)
            {
                return;
            }


            if (string.IsNullOrEmpty(recaptchaUserValue.Value))
            {
                Msg.Visible   = true;
                Msg.InnerHtml = "Error en los datos de seguridad, vuelva a recargar la página.";
                return;
            }


            var Recaptchav3 = new RecaptchaVerificationHelper();

            // If your site is behind CloudFlare, be sure you're suing the CF-Connecting-IP header value instead:
            // https://support.cloudflare.com/hc/en-us/articles/200170986-How-does-Cloudflare-handle-HTTP-Request-headers

            RecaptchaVerificationResult recaptchaResult = Recaptchav3.VerifyRecaptchav3Response(
                Global.Configuration.Security.Google.Recaptcha.v3.GetGoogleRecaptchaSecretKey()
                , Global.Configuration.Security.Google.Recaptcha.v3.GetGoogleRecaptchaWebsiteKey()
                , Request.UserHostAddress
                , recaptchaUserValue.Value
                );

            if (recaptchaResult == RecaptchaVerificationResult.Success)
            {
                //divMessage.InnerHtml = "Score: " + Recaptchav3.Score;
                decimal?minScore = new decimal(0.6);
                if (Recaptchav3.Score < minScore)
                {
                    Response.Redirect("~/Captcha.aspx", true);
                }


                //create session
                // Global.Sessions.UserCreateSession();

                // Go main menu.
                if (ValidateLogin())
                {
                    HttpCookie userid = new HttpCookie("User.Email", Email.Value.ToString())
                    {
                        Expires = DateTime.Now.AddYears(1)
                    };
                    Response.Cookies.Add(userid);

                    Response.Redirect("~/recursos/");
                }
                else
                {
                    Msg.Visible = true;
                }
                Msg.InnerHtml = "Login fallido. Por favor revise sus datos e intente de nuevo.";
            }
            else
            {
                Msg.Visible   = true;
                Msg.InnerHtml = "Existe un problema para validar la seguridad, intente mas tarde o por favor contacte a soporte técnico.";
            }



            bool ValidateLogin()
            {
                bool   loginOK = false;
                string salt = string.Empty, encrypass = string.Empty, dbpassword = string.Empty;

                SqlParameter[] parameters =
                {
                    new SqlParameter {
                        ParameterName = "Email", DbType = DbType.AnsiString, Size = 50, Value = Email.Value.ToString()
                    }
                };

                string tsql      = @"
SELECT TOP 1 
       [UserRegisterID]
      ,[Names]
      ,[LastName]
      ,[Email]
      ,[Password]
      ,[PasswordSalt]
  FROM [CMSUserRegister]
WHERE
Email = @Email 
ORDER BY [UserRegisterID] DESC
;";
                var    sqlserver = new SqlApiSqlClient();


                using (sqlserver.Connection = new SqlConnection(Global.Configuration.DB.GetConnectionStringDBMain()))
                {
                    using (var dr = sqlserver.DataReaderSqlString(tsql, parameters))
                    {
                        if (dr.Read())
                        {
                            salt       = dr["PasswordSalt"].ToString();;
                            dbpassword = dr["Password"].ToString();;


                            Byte[] _salt;
                            Byte[] _hash;

                            //This is the password policy that all passwords must adhere to, if the password doesn't meet the policy we save CPU processing time by not even bothering to calculate hash of a clearly incorrect password
                            PWDTK.PasswordPolicy PwdPolicy = new PWDTK.PasswordPolicy(numberUpper, numberNonAlphaNumeric, numberNumeric, minPwdLength, maxPwdLength);

                            //or we can just use the default password policy provided by the API like below
                            //PWDTK.PasswordPolicy PwdPolicy = PWDTK.cDefaultPasswordPolicy;

                            _salt = PWDTK.HashHexStringToBytes(salt); // reverse operation ;

                            //Generate the hash value
                            _hash = PWDTK.PasswordToHash(_salt, Password.Value.ToString(), iterations);

                            encrypass = PWDTK.HashBytesToHexString(_hash);


                            if (encrypass == dbpassword)
                            {
                                loginOK = true;

                                // Session["User.UserEmail"] = dr["UserEmail"].ToString();
                            }
                            else
                            {
                                loginOK = false;
                            }
                        }
                        else
                        {
                            loginOK = false;
                        }

                        dr.Close();
                    }

                    sqlserver.Connection.Close();
                };


                if (loginOK)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        }
Exemple #9
0
 /// <summary>
 /// Gera um salt aleatório e usa para encriptografar a <paramref name="senha"/>.
 /// </summary>
 /// <param name="senha">Senha a ser encriptografada.</param>
 /// <param name="salt">Salt que é gerado. Deve-se guardá-lo no banco.</param>
 /// <returns>O hash gerado</returns>
 public static byte[] Encriptar(string senha, out byte[] salt)
 {
     salt = PWDTK.GetRandomSalt();
     return(PWDTK.PasswordToHash(salt, senha));
 }
        /*
         * bool IsUserAlreadyExist()
         * {
         *
         *  SqlParameter[] parameters = {
         *      new SqlParameter { ParameterName="UserLogin", DbType= DbType.AnsiString, Size=128, Value= Email.Value.ToString()}
         *
         *  };
         *
         *  string email = SqlApiSqlClient.GetStringRecordValue("SELECT [UserLogin] FROM Users WHERE [UserLogin] = @UserLogin;", parameters, Global.Configuration.DB.GetConnectionStringDBMain());
         *
         *  if (!string.IsNullOrEmpty(email)) return true;
         *  else return false;
         *
         * }
         */

        //TODO: send confirmation email
        bool CreateUser()
        {
            string salt, encrypass;

            Byte[] _salt;
            Byte[] _hash;

            //This is the password policy that all passwords must adhere to, if the password doesn't meet the policy we save CPU processing time by not even bothering to calculate hash of a clearly incorrect password
            PWDTK.PasswordPolicy PwdPolicy = new PWDTK.PasswordPolicy(numberUpper, numberNonAlphaNumeric, numberNumeric, minPwdLength, maxPwdLength);

            //or we can just use the default password policy provided by the API like below
            //PWDTK.PasswordPolicy PwdPolicy = PWDTK.cDefaultPasswordPolicy;

            //Get a random salt
            _salt = PWDTK.GetRandomSalt(saltSize);
            //Generate the hash value
            _hash = PWDTK.PasswordToHash(_salt, PasswordReg.Value.ToString(), iterations);

            encrypass = PWDTK.HashBytesToHexString(_hash);
            salt      = PWDTK.HashBytesToHexString(_salt); // reverse operation PWDTK.HashHexStringToBytes();


            SqlParameter[] parameters =
            {
                new SqlParameter {
                    ParameterName = "Names", DbType = DbType.AnsiString, Size = 50, Value = Names.Value.ToString()
                }
                , new SqlParameter{
                    ParameterName = "LastName", DbType = DbType.AnsiString, Size = 50, Value = LastName.Value.ToString()
                }
                , new SqlParameter{
                    ParameterName = "Mobile", DbType = DbType.AnsiString, Size = 50, Value = Mobile.Value.ToString()
                }
                , new SqlParameter{
                    ParameterName = "Email", DbType = DbType.AnsiString, Size = 50, Value = Email.Value.ToString()
                }
                , new SqlParameter{
                    ParameterName = "Business", DbType = DbType.AnsiString, Size = 50, Value = Business.Value.ToString()
                }
                , new SqlParameter{
                    ParameterName = "Position", DbType = DbType.AnsiString, Size = 50, Value = Position.Value.ToString()
                }
                , new SqlParameter{
                    ParameterName = "Country", DbType = DbType.AnsiString, Size = 50, Value = Country.Value.ToString()
                }
                , new SqlParameter{
                    ParameterName = "City", DbType = DbType.AnsiString, Size = 50, Value = City.Value.ToString()
                }
                , new SqlParameter{
                    ParameterName = "Telephone", DbType = DbType.AnsiString, Size = 50, Value = Telephone.Value.ToString()
                }
                , new SqlParameter{
                    ParameterName = "Password", DbType = DbType.AnsiString, Size = 1000, Value = encrypass
                }
                , new SqlParameter{
                    ParameterName = "PasswordSalt", DbType = DbType.AnsiString, Size = 1000, Value = salt
                }
            };

            string tsql      = @"
SET NOCOUNT OFF;
INSERT INTO [CMSUserRegister] ([Names], [LastName], [Mobile], [Email], [Business], [Position], [Country], [City], [Telephone], [RegisterDate], [Password], [PasswordSalt], [LastLogin]) VALUES (@Names, @LastName, @Mobile, @Email, @Business, @Position, @Country, @City, @Telephone, GETDATE(), @Password, @PasswordSalt, GETDATE());
; ";
            var    sqlserver = new SqlApiSqlClient();
            int    r         = sqlserver.CommandExecuteSqlString(tsql, parameters, Global.Configuration.DB.GetConnectionStringDBMain());

            if (r == 1)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }