Beispiel #1
0
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            Log.Debug("Started validating user credential for password change.");
            if (ModelState.IsValid)
            {
                var crypto = new PBKDF2();
                var user   = userService.GetUsers().FirstOrDefault(u => u.UserName == User.Identity.Name);

                if (user.Password == crypto.Compute(model.OldPassword, user.PasswordSalt))
                {
                    user.Password        = crypto.Compute(model.NewPassword);
                    user.ConfirmPassword = crypto.Compute(model.ConfirmPassword);

                    try
                    {
                        userService.UpdateUser(user);
                    }
                    catch (Exception e)
                    {
                        Log.Error(e.ToString());
                    }

                    return(RedirectToAction("ChangePasswordSuccess"));
                }
            }
            Log.Info("The password was not succesfully changed.");

            ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");

            return(View(model));
        }
Beispiel #2
0
 public override void Validate(string userName, string password)
 {
     using (var context = new AF_Context())
     {
         const string   pepper        = "50.L1`(f761OJdG6fc835M(5(+Ju2!P6,4330_N*/%xz<j7(N15KC'8l997'0c0CEg";
         ICryptoService cryptoService = new PBKDF2();
         try
         {
             User u = context.Users.FirstOrDefault(c => c.Login == userName);
             if (u == null)
             {
                 throw new SecurityTokenException("Wrong Username or Password");
             }
             bool verified = cryptoService.Compare(cryptoService.Compute(cryptoService.Compute(password, u.Salt), pepper), u.Password);
             if (!verified)
             {
                 throw new SecurityTokenException("Wrong Username or Password");
             }
         }
         catch (Exception ex)
         {
             throw;
         }
     }
 }
        static void Main(string[] args)
        {
            string         pass          = "";
            int            id            = 0;
            ICryptoService cryptoService = new PBKDF2();
            const string   pepper        = "50.L1`(f761OJdG6fc835M(5(+Ju2!P6,4330_N*/%xz<j7(N15KC'8l997'0c0CEg";

            Console.WriteLine("Select user by id:");
            if (int.TryParse(Console.ReadLine(), out id))
            {
                using (var context = new AF_Context())
                {
                    try
                    {
                        User user = context.Users.First(u => u.UserId == id);
                        if (user != null)
                        {
                            while (string.IsNullOrEmpty(pass))
                            {
                                Console.WriteLine("Input Password:");
                                pass = Console.ReadLine();
                            }
                            user.Salt     = cryptoService.GenerateSalt();
                            user.Password = cryptoService.Compute(cryptoService.Compute(pass, user.Salt), pepper);
                        }
                        context.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        throw;
                    }
                }
            }
        }
Beispiel #4
0
        /// <summary>
        /// Generate password hash and salt
        /// </summary>
        /// <param name="password">plaintext password</param>
        /// <returns></returns>
        public static string[] Hash(string password, string saltStr = null)
        {
            string hash;
            string salt;
            var    CryptoSvc = new PBKDF2();

            // generate new hash
            if (saltStr == null)
            {
                hash = CryptoSvc.Compute(password);
                salt = CryptoSvc.Salt;
                return(new string[]
                {
                    hash,
                    salt
                });
            }

            else
            {
                hash = CryptoSvc.Compute(password, saltStr);
                return(new string[]
                {
                    hash,
                    ""
                });
            }
        }
Beispiel #5
0
        protected void btnIniciar_Click(object sender, EventArgs e)
        {
            string user = txtUser.Text.Trim();
            string pas  = txtPass.Text.Trim();

            if (user != "" && pas != "")
            {
                var persona = instaciaBD.tbl_persona.Where(x => x.usuarioPersona == user).FirstOrDefault();


                if (persona != null)
                {
                    ICryptoService encripto      = new PBKDF2();//INSTANCIO EL ALGORITMO
                    string         pasEncriptada = encripto.Compute(pas, persona.salt);
                    if (encripto.Compare(persona.contrasenaPersona, pasEncriptada))
                    {
                        FormsAuthentication.SetAuthCookie(persona.nombrePersona + " " + persona.apellidoPersona, true);
                        Response.Redirect("Inicio.aspx");
                    }
                    else
                    {
                        ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "aletarLoginFail", "window.onload = function(){ alert ('Contraseña incorrecta');};", true);
                    }
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "aletarLoginFail", "window.onload = function(){ alert ('no existe ');};", true);
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "aletarLoginFail", "window.onload = function(){ alert ('debe ingresar datos');};", true);
            }
        }
Beispiel #6
0
        public ActionResult create(tbl_usuario usuario)
        {
            //LLAMO AL METODO Y HASHEO LA CONTRASEÑA
            string co = GetSHA1(usuario.contrasena);

            ICryptoService cryptoService = new PBKDF2();
            //Generar algoritmo de encryptacion
            string salt = cryptoService.GenerateSalt();
            string contrasenaencryptada = cryptoService.Compute(usuario.contrasena);

            conexion.Open();
            SqlCommand query = new SqlCommand("insertarusuario", conexion);

            query.CommandType = CommandType.StoredProcedure;
            query.Parameters.Add("@pid_usuario", SqlDbType.VarChar).Value      = usuario.id_usuario;
            query.Parameters.Add("@pcontrasena", SqlDbType.VarChar).Value      = co;
            query.Parameters.Add("@pnombre_usuario", SqlDbType.VarChar).Value  = usuario.nombre_usuario;
            query.Parameters.Add("@ppaterno_usuario", SqlDbType.VarChar).Value = usuario.paterno_usuario;
            query.Parameters.Add("@pmaterno_usuario", SqlDbType.VarChar).Value = usuario.materno_usuario;
            query.Parameters.Add("@ptipo_usuario", SqlDbType.VarChar).Value    = usuario.tipo_usuario;
            query.Parameters.Add("@pcorreo", SqlDbType.VarChar).Value          = usuario.correo;
            query.ExecuteNonQuery();
            conexion.Close();
            return(RedirectToAction("Index"));
        }
        private bool isValid(string email, string password, ref string errore, ref PERSONA utente)
        {
            bool   flag;
            PBKDF2 crypto = new PBKDF2();

            using (DatabaseContext db = new DatabaseContext())
            {
                utente = db.PERSONA_EMAIL.Where(u => u.EMAIL == email && u.PERSONA.STATO == (int)Stato.ATTIVO).Select(u => u.PERSONA).SingleOrDefault();
                //utente = db.PERSONA.FirstOrDefault<PERSONA>((PERSONA u) => u.EMAIL == email && u.STATO == 1);
                if (utente == null)
                {
                    errore = Language.EmailNotExist;
                }
                else if (!utente.PASSWORD.Equals(crypto.Compute(password, utente.TOKEN_PASSWORD)))
                {
                    errore = Language.ErrorPassword;
                }
                else
                {
                    flag = true;
                    return(flag);
                }
            }
            flag = false;
            return(flag);
        }
Beispiel #8
0
        private static bool ValidatePassword(string password, string salt, string hashedPassword)
        {
            ICryptoService cryptoService   = new PBKDF2();
            string         hashedPassword2 = cryptoService.Compute(password, salt);

            return(cryptoService.Compare(hashedPassword, hashedPassword2));
        }
        public ActionResult Index(string eMail, string pass)
        {
            if (Request["Email"] == null || Request["Password"] == null)
            {
                return(View());
            }
            string email    = Request["Email"].ToString();
            string password = Request["Password"].ToString();

            //check if user exists and password matches
            var user = db.Employees.FirstOrDefault(e => e.EmployeeEmail == email);

            if (user != null)
            {
                ICryptoService cryptoService = new PBKDF2();

                string hashed = cryptoService.Compute(password, user.Salt);

                if (hashed == user.Pass)
                {
                    Session["userLoggedIn"] = user.EmployeeEmail;
                    return(RedirectToAction("Index", "Students"));
                }
            }

            return(View());
        }
Beispiel #10
0
        private void btnAuth_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(PasswordUser))
            {
                MessageBox.Show("Пароль пустий.");
                return;
            }
            var user = GetUserByEmail(EmailLogin);

            if (user != null)
            {
                ICryptoService cryptoService = new PBKDF2();
                // validate user
                string password        = PasswordUser;
                string salt            = user.PasswordHash;
                string hashedPassword2 = cryptoService.Compute(password, salt);
                bool   isPasswordValid = cryptoService.Compare(user.Password, hashedPassword2);
                if (isPasswordValid)
                {
                    DialogResult = DialogResult.OK;
                }
                else
                {
                    MessageBox.Show("Неправильний пароль або емейл, спробуйте ще раз.");
                }
            }
            else
            {
                MessageBox.Show("Неправильний пароль або емейл, спробуйте ще раз.");
            }
        }
Beispiel #11
0
        public ActionResult Create([Bind(Include = "EmployeeID,EmployeeName,EmployeeSurname,EmployeeEmail,Pass")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                //hash password
                ICryptoService cryptoService = new PBKDF2();

                //save this salt to the database
                string salt = cryptoService.GenerateSalt();

                //save this hash to the database
                if (string.IsNullOrEmpty(employee.Pass))
                {
                    employee.Pass = "******";
                }
                string hashedPassword = cryptoService.Compute(employee.Pass);
                employee.Salt = salt;
                employee.Pass = hashedPassword;

                if (db.Employees.FirstOrDefault(e => e.EmployeeEmail == employee.EmployeeEmail) == null)
                {
                    db.Employees.Add(employee);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }

            return(View(employee));
        }
Beispiel #12
0
        public User RegisterUser(RegisterUserViewModel user)
        {
            using (TransactionScope scope = new TransactionScope())
            {
                var el = _context.Users.SingleOrDefault(m => m.Email == user.Email);
                if (el != null)
                {
                    return(null);
                }

                ICryptoService cryptoService  = new PBKDF2();
                string         passwordSalt   = cryptoService.GenerateSalt();
                string         hashedPassword = cryptoService.Compute(user.Password);
                Role           userRole       = _context.Roles.SingleOrDefault(m => m.Name == "User");
                User           newUser        = new User
                {
                    FullName          = user.FullName,
                    Email             = user.Email,
                    Password          = hashedPassword,
                    PasswordSalt      = passwordSalt,
                    Roles             = new List <Role>(),
                    EmailConfirmed    = false,
                    EmailConfirmToken = Guid.NewGuid().ToString()
                };

                if (userRole != null)
                {
                    newUser.Roles.Add(userRole);
                }
                _context.Users.Add(newUser);
                _context.SaveChanges();
                scope.Complete();
                return(newUser);
            }
        }
        public async Task <ActionResult> CreateAsync(UserViewModel userVM)
        {
            User user = new User
            {
                Id             = userVM.Id,
                IdentityNumber = userVM.IdentityNumber,
                Name           = userVM.Name,
                LastName       = userVM.LastName,
                Email          = userVM.Email,
                IsActive       = userVM.IsActive,
                Phone          = userVM.Phone,
                RoleId         = userVM.RoleId,
            };

            ICryptoService cryptoService = new PBKDF2();
            //New User
            string password = userVM.Password;
            //save this salt to the database
            string passwordHashedSalt = cryptoService.GenerateSalt();
            //save this hash to the database
            string passwordHashed = cryptoService.Compute(password);

            user.PasswordHashedSalt = passwordHashedSalt;
            user.PasswordHashed     = passwordHashed;

            if (ModelState.IsValid)
            {
                _context.Add(user);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(userVM));
        }
Beispiel #14
0
        // оновлюємо пароль користувача
        private void btChangePass_Click(object sender, EventArgs e)
        {
            if (txtNewPass.Text == "")
            {
                MessageBox.Show("Пароль не може бути порожнім, внесіть значення");
            }
            else
            {
                ICryptoService cryptoService  = new PBKDF2();
                string         salt           = cryptoService.GenerateSalt();
                string         hashedPassword = cryptoService.Compute(txtNewPass.Text);

                try
                {
                    string strCon = @"Data Source=dell7020\sqlexpress;Initial Catalog=GridUserForm;Integrated Security=True";
                    using (SqlConnection con = new SqlConnection(strCon))
                    {
                        {
                            con.Open();
                            SqlCommand command = new SqlCommand();
                            command.Connection = con;
                            string query = $"UPDATE [dbo].[tblUsers] SET Password = '******', PasswordSalt = '{salt}' WHERE tblUsers.Id = {id}";
                            command.CommandText = query;
                            command.ExecuteNonQuery();
                            MessageBox.Show("Пароль змінено");
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Помилка оновлення паролю {ex.Message}", ex.Message);
                }
            }
        }
Beispiel #15
0
        protected bool IsValidNuGetApiKey(INancyModule module, IFeed feed)
        {
            if (!string.IsNullOrWhiteSpace(feed.ApiKeyHashed))
            {
                if (module.Request.Headers[NuGetHeaderApiKeyName].FirstOrDefault() == null)
                {
                    return(false);
                }

                ICryptoService cryptoService = new PBKDF2();

                var feedApiKeyHashed = feed.ApiKeyHashed;
                var feedApiKeySalt   = feed.ApiKeySalt;

                var requestApiKey = module.Request.Headers[NuGetHeaderApiKeyName].FirstOrDefault();

                if (string.IsNullOrWhiteSpace(requestApiKey))
                {
                    return(false);
                }

                string requestApiKeyHashed = cryptoService.Compute(requestApiKey, feedApiKeySalt);
                bool   isValidApiKey       = cryptoService.Compare(requestApiKeyHashed, feedApiKeyHashed);

                if (!isValidApiKey)
                {
                    return(false);
                }
            }
            return(true);
        }
Beispiel #16
0
        protected void btnRecuperar_Click(object sender, EventArgs e)
        {
            string usuario = txtUsuario.Text.Trim();

            var persona = db.Persona.Where(x => x.usuario == usuario).FirstOrDefault();

            if (persona != null)
            {
                ICryptoService cryptoService = new PBKDF2();

                string contrasennaNueva = RandomPassword.Generate(10, PasswordGroup.Lowercase, PasswordGroup.Uppercase, PasswordGroup.Numeric, PasswordGroup.Special);

                string salt = cryptoService.GenerateSalt();
                string contrasennaCryptada = cryptoService.Compute(contrasennaNueva);

                try
                {
                    persona.salt        = salt;
                    persona.contrasenna = contrasennaCryptada;
                    db.SubmitChanges();
                    enviarEmail(persona.email, contrasennaNueva);
                }
                catch (Exception) {
                    throw;
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "alertaUsuario", "window.onload = function(){alert('El usuario no existe.');};", true);
            }
        }
        // https://github.com/shawnmclean/SimpleCrypto.net
        public static bool IsPasswordValid(string password, string storedPasswordHash, string salt)
        {
            ICryptoService cryptoService   = new PBKDF2();
            string         hashedPassword2 = cryptoService.Compute(password, salt);

            return(cryptoService.Compare(storedPasswordHash, hashedPassword2));
        }
Beispiel #18
0
        public List <Tbl_Usuario> IniciarSesion(string usuario, string contrasenia)
        {
            //Encriptar Contraseña
            ICryptoService cryptoService         = new PBKDF2();
            string         ContraseniaEncriptada = cryptoService.Compute(contrasenia, SaltEncriptar);

            return(objetoCD.UsuarioLogin(usuario, ContraseniaEncriptada));
        }
Beispiel #19
0
        public static string GetPasswordHash(string password)
        {
            ICryptoService cryptoService   = new PBKDF2();
            int            SALT_SIZE       = 16;
            int            HASH_ITERATIONS = 20;

            return(cryptoService.Compute(password, SALT_SIZE, HASH_ITERATIONS));
        }
Beispiel #20
0
        protected void Iniciar_Click(object sender, EventArgs e)
        {
            Session["help"] = 2;
            label1.Visible  = false;
            List <Usuarios> allUser = new List <Usuarios>();

            allUser = SIRESEP.BS.ManUsuario._Instancia.Mostrar();

            int largo = Convert.ToInt32(allUser.Count.ToString());

            Session["help"] = 1;
            Session.Add("usuario", "valor");

            for (int i = 0; i < largo; i++)
            {
                String user  = allUser[i]._cedula.ToString();
                String pass  = allUser[i]._contrasena.ToString();
                String salt  = allUser[i]._salt.ToString();
                String idRol = allUser[i]._idRol.ToString();



                String exUser = cedula.Value.Trim();
                String exPass = inputPassword.Value.Trim();
                //Encriptar la contraseña y comparar para verificar que la registrada sea la misma usando el mismo algoritmo que tiene en la base
                ICryptoService cryptoService = new PBKDF2();
                string         contraEncrip  = cryptoService.Compute(exPass, salt);


                if (exUser.Equals(user) && contraEncrip.Equals(pass))
                {
                    if (idRol.Equals("1"))
                    {
                        //se hacen 'secciones' para indicar el tipo de usuario, ademas sirve para evitar acceder a las paginas si no es el usuario correcto
                        // tambien sirve para cambiar el master page en las paginas compartidas como carrera, grado de estudio e idioma
                        Session.Add("admin", "valor");
                        Response.Redirect("FrInicioAdmin.aspx");
                    }
                    if (idRol.Equals("2"))
                    {
                        string ced = exUser.Trim();
                        Session["ced"] = ced;
                        Session.Add("usuario", "valor");
                        Response.Redirect("FrInicioUser.aspx");
                        usuario._cedula = cedula.Value;
                    }
                    else
                    {
                        label1.Visible = true;
                    }


                    if (idRol.Equals("3"))
                    {
                    }
                }
            }
        }
        private string HashPassword(string password)
        {
            var cryptoService = new PBKDF2();

            // TODO: store in some securure place
            var salt = "100000.i7BB2tLt5UeYA9qDTRySyFjIJGgEZTDAFfesZeEr2mJqxA==";

            return(cryptoService.Compute(password, salt));
        }
    public override bool ChangePassword(string username, string oldPassword, string newPassword)
    {
        // Hash the password using our currently configured salt size and hash iterations
        PBKDF2 crypto = new PBKDF2();

        crypto.HashIterations = HashIterations;
        crypto.SaltSize       = SaltSize;
        string oldHash = crypto.Compute(oldPassword);
        string salt    = crypto.Salt;
        string newHash = crypto.Compute(oldPassword);

        using (SqlConnection con = new SqlConnection(this.connectionString))
        {
            con.Open();
            con.Close();
        }
        return(true);
    }
Beispiel #23
0
        !(new Regex(@" ").IsMatch(value));                                                      //Don't have white spaces

        public string GetHash(string salt)
        {
            if (_secureString.IsNotNull() && !string.IsNullOrEmpty(salt))
            {
                Value = PBKDF2.Compute(Marshal.PtrToStringUni(Marshal.SecureStringToBSTR(_secureString)), salt);
            }

            return(Value);
        }
Beispiel #24
0
        private static PasswordCrypto EncryptPassword(string password)
        {
            ICryptoService cryptoService = new PBKDF2();
            var            crypto        = new PasswordCrypto();

            crypto.Salt     = cryptoService.GenerateSalt();
            crypto.Password = cryptoService.Compute(password);
            return(crypto);
        }
        public static Tuple <string, string> HashPassword(string password)
        {
            ICryptoService cryptoService = new PBKDF2();

            string salt           = cryptoService.GenerateSalt();
            string hashedPassword = cryptoService.Compute(password, salt);

            return(new Tuple <string, string>(hashedPassword, salt));
        }
Beispiel #26
0
        public void InsertarUsuario(string cedula, string nombre, string direccion, string telefono, string correo, string usuario, string contrasenia, string rol, string foto)
        {
            //Encriptar Contraseña
            ICryptoService cryptoService          = new PBKDF2();
            string         Salt_Contrasenia       = cryptoService.GenerateSalt();
            string         Contrasenia_Encriptada = cryptoService.Compute(contrasenia);

            objetoCD.Insertar(cedula, nombre, direccion, telefono, correo, usuario, Contrasenia_Encriptada, Salt_Contrasenia, Convert.ToInt32(rol), foto);
        }
Beispiel #27
0
        public void CambiarContrasenia(string NuevaContrasenia, string IdUsuario)
        {
            //Encriptar Contraseña
            ICryptoService cryptoService          = new PBKDF2();
            string         Salt_Contrasenia       = cryptoService.GenerateSalt();
            string         Contrasenia_Encriptada = cryptoService.Compute(NuevaContrasenia);

            objetoCD.CambiarContrasenia(Contrasenia_Encriptada, Salt_Contrasenia, Convert.ToInt32(IdUsuario));
        }
        // GET: Moviles
        public ActionResult Acceso(string correo, string password)

        {
            string constr  = conexion;
            string constr1 = conexion1;

            vista = "../Login/Login";
            System.Web.HttpContext.Current.Session["acceso"] = "Usuario no encontrado";
            using (MySqlConnection con = new MySqlConnection(constr))
            {
                string query = "select * from web_usuarios_login WHERE Cod_Usuario = '" + correo + "'";
                using (MySqlCommand cmd = new MySqlCommand(query))
                {
                    cmd.Connection = con;
                    con.Open();
                    using (MySqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            ICryptoService cryptoService      = new PBKDF2();
                            string         PasswordEncriptada = cryptoService.Compute(password, sdr["Salt"].ToString());
                            if (sdr.HasRows)
                            {
                                System.Web.HttpContext.Current.Session["sessionClosed"] = null;
                                if (cryptoService.Compare(sdr["Password"].ToString(), PasswordEncriptada))
                                {
                                    System.Web.HttpContext.Current.Session["sessionString"] = sdr["Nombre"].ToString() + " " + sdr["Apellido"].ToString();
                                    System.Web.HttpContext.Current.Session["perfil"]        = sdr["Cod_Perfil"].ToString();
                                    System.Web.HttpContext.Current.Session["correo"]        = sdr["Cod_Usuario"].ToString();
                                    vista = "../Principal/Principal";
                                }
                            }
                        }
                    }
                    con.Close();
                }
            }
            using (MySqlConnection con1 = new MySqlConnection(constr1))
            {
                string querypararm = "select * from web_vparam_sys";
                using (MySqlCommand cmd1 = new MySqlCommand(querypararm))
                {
                    cmd1.Connection = con1;
                    con1.Open();
                    using (MySqlDataReader sdr1 = cmd1.ExecuteReader())
                    {
                        while (sdr1.Read())
                        {
                            System.Web.HttpContext.Current.Session["conductoresConf"] = sdr1["Varios_Conductores"].ToString();
                        }
                    }
                    con1.Close();
                }
            }
            return(RedirectToAction(vista));
        }
        public static IEnumerable PBKDF2HashList(string text, string salt)
        {
            ICryptoService cryptoService = new PBKDF2();
            ArrayList      hashedText    = new ArrayList();
            string         hash;

            if (salt == null)
            {
                hash = cryptoService.Compute(text, 16, 5000);
                salt = cryptoService.Salt;
            }
            else
            {
                hash = cryptoService.Compute(text, salt);
            }

            hashedText.Add(new HashedBytes(hash, salt));

            return(hashedText);
        }
Beispiel #30
0
        protected void buttonPBKDF2_Click(object sender, EventArgs e)
        {
            if (passwordNotEnteredError())
            {
                return;
            }

            var    pbkdf2Encryptor = new PBKDF2();
            string encryptedPass   = pbkdf2Encryptor.Compute(TextBox1.Text);

            Response.Write($"Your PBKDF2 encryption is {encryptedPass}");
        }