public OperationResult <User> Register(User model) { try { var existingUser = _userRepository.Read().FindByAny(model.Name, model.Email, model.DisplayName); if (existingUser != null) { if (existingUser.Name == model.Name) { return(new OperationResult <User>(OperationResultType.ValidationFailed, null, ServicesMessages.User_Validation_NameAlreadyExists.FormatSafe(model.Name))); } if (existingUser.DisplayName == model.DisplayName) { return(new OperationResult <User>(OperationResultType.ValidationFailed, null, ServicesMessages.User_Validation_DisplayNameAlreadyExists.FormatSafe(model.DisplayName))); } if (existingUser.Email == model.Email) { return(new OperationResult <User>(OperationResultType.ValidationFailed, null, ServicesMessages.User_Validation_EmailAlreadyExists.FormatSafe(model.Email))); } Log.Error("Unknown error during registering user of name: " + model.Name, null); return(new OperationResult <User>(OperationResultType.Error, null)); } else { var now = DateTime.Now; var userToAdd = new User { Country = model.Country, DisplayName = model.DisplayName, Email = model.Email, Name = model.Name, Password = _cryptoService.Compute(model.Password, null), RegisteredAt = now, LastLogInAt = now, Sex = model.Sex }; userToAdd.UserAddress = new UserAddress { User = userToAdd }; userToAdd.UserDetail = new UserDetail { User = userToAdd }; userToAdd.UserPersonal = new UserPersonal { User = userToAdd }; _userRepository.Create(userToAdd); _unitOfWork.Commit(); return(new OperationResult <User>(OperationResultType.Success, userToAdd)); } } catch (Exception exception) { var userName = model == null ? null : model.Name; Log.Error("Exception during registering user of name: " + userName, exception); return(new OperationResult <User>(OperationResultType.Error, null, ServicesMessages.Error_Unknown)); } }
public IPassword Generate() { var clear = RandomPassword.Generate(PasswordCharactersCount); var salt = cryptoService.GenerateSalt(); var hash = cryptoService.Compute(clear, salt); return(new Password() { Clear = clear, Hash = hash, Salt = salt }); }
public User GetUser(string login, string password) { var user = _repo.Query(u => u.UserName.ToLower() == login.ToLower()).FirstOrDefault(); if (user != null) { if (user.Password == _crypto.Compute(password, user.PasswordSalt)) { return(user); } } return(null); }
protected void btnRecuperar_Click(object sender, EventArgs e) { string user = txtUser.Text; var persona = instanciBD.tbl_persona.Where(x => x.usuarioPersona == user).FirstOrDefault(); if (persona != null) { string newPasEncriptada = RandomPassword.Generate(10, PasswordGroup.Lowercase, PasswordGroup.Uppercase, PasswordGroup.Numeric, PasswordGroup.Special); //la cantidad de argumentos, minusculas, mayusculas/ numeros y caracteres especiales string salt = encriptado.GenerateSalt(); string contrasenaEncriptada = encriptado.Compute(newPasEncriptada); try { persona.salt = salt; persona.contrasenaPersona = contrasenaEncriptada; instanciBD.SubmitChanges(); EnviarCorreo(persona.emailPersona, newPasEncriptada); } catch (Exception) { throw; } } else { ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "aletarUsuario", "window.onload = function(){ alert ('Usuario No esta');};", true); } }
public HashedText ComputeHash(string text, string salt) { var saltAndText = String.Concat(text, salt); return(new HashedText { Salt = salt, Text = _cryptoService.Compute(saltAndText, salt) }); }
public void Login(string email, string pass, int perfil) { var list = bd.usuarios.Where(x => x.email == email && x.idperfil == perfil).FirstOrDefault(); if (list != null) { passEncryptada = cryptoService.Compute(pass, list.salt); if (cryptoService.Compare(list.pass, passEncryptada)) { var lista = (from us in bd.usuarios join pe in bd.personas on us.idpersona equals pe.id where us.id == list.id select new { id = us.id, idperfil = us.idperfil, idpersona = us.idpersona, nombre = pe.nombre, apellido = pe.apellido, telefono = pe.telefono, sexo = pe.sexo, curp = pe.curp, fechanacimiento = pe.fechanacimiento, longi = pe.@long, lat = pe.lat, idinteres = pe.idinteres, fotoperfil = pe.fotoperfil }).ToList(); json = JsonConvert.SerializeObject(lista); } else { json = JsonConvert.SerializeObject("[{ mensaje : '1' }]"); //La contraseƱa es incorrecta } } else { json = JsonConvert.SerializeObject("[{mensaje : '0'}]");// el usuario no existe u el perfil es incorrecto } con.Response.Write(json); con.Response.End(); }
public bool ValidatePasswordAgainstHash(string password, string salt, string knownHash) { if (string.IsNullOrEmpty(password) || string.IsNullOrEmpty(salt)) { return(false); } var passwordHash = _cryptoService.Compute(password, salt); return(_cryptoService.Compare(passwordHash, knownHash)); }
public static void CreateUser(string username) { Console.WriteLine("New user creation."); bool validNewUser; string password = ""; do { try { Console.WriteLine("Password: "******"Confirm password: "******"Please confirm your passwords match."); } } catch (Exception e) { Console.WriteLine(e.Message); validNewUser = false; } }while (validNewUser == false); User user = new User { UserName = username, Salt = cryptoService.GenerateSalt(), Password = cryptoService.Compute(password) }; db.Users.InsertOnSubmit(user); db.SubmitChanges(); }
public async Task LoginAsync(string email, string password) { var user = await _userRepository.GetByEmailAsync(email); if (user == null) { throw new OcenUczelnieException(ErrorCodes.InvalidCredentials); } var generatedHash = _cryptoService.Compute(password, user.Salt); if (!_cryptoService.Compare(generatedHash, user.Password)) { throw new OcenUczelnieException(ErrorCodes.InvalidCredentials); } if (!user.IsConfirmed) { throw new OcenUczelnieException(ErrorCodes.NotActivated, "User is not activated."); } var token = _tokenProvider.CreateToken(user.Id, user.Role); _memoryCache.Set("generatedToken", token, TimeSpan.FromSeconds(5)); }
public IActionResult EditPassword(string username, [FromForm] UserEditPasswordRequest editRequest) { var userId = AuthController.GetUserIdFromPrincipal(Request, config.Secret); var user = authUnit.Users.GetUserById(userId); // Validate user if (user == null) { return(NotFound()); } if (user.Username != username) { return(Unauthorized()); } // Compare existing password var oldHash = cryptoService.Compute(editRequest.OldPassword, user.PasswordSalt); if (!cryptoService.Compare(user.Password, oldHash)) { return(BadRequest()); } // Set new password var newHash = cryptoService.Compute(editRequest.NewPassword); user.Password = newHash; user.PasswordSalt = cryptoService.Salt; authUnit.Users.UpdateUser(user); authUnit.Complete(); return(NoContent()); }
private void Guardar() { pnlAlertaError.Visible = false; PanelAlerta.Visible = false; string nombre = txtNombrePersona.Text.Trim(); string apellido = txtApellido.Text.Trim(); string user = txtUsuario.Text.Trim(); string contra = txtContrasena.Text.Trim(); string mail = txtCorreo.Text.Trim(); int edad = int.Parse(txtEdad.Text.Trim()); /*instanciaBd.sp_CrearCliente(nombre, apellido, user, contra, "", byte.Parse(edad.ToString()));*/ tbl_persona una = new tbl_persona(); //GENERAR ENCRIPTACION string saltAlgoritmoEncriptacion = encripto.GenerateSalt(); string contrasenaEncriptada = encripto.Compute(contra); una.nombrePersona = nombre; una.apellidoPersona = apellido; una.usuarioPersona = user; una.contrasenaPersona = contrasenaEncriptada; una.edad = Convert.ToByte(edad); una.salt = saltAlgoritmoEncriptacion; una.estado = 1; una.idTipoPersona = 2; una.emailPersona = mail; try { instanciaBd.tbl_persona.InsertOnSubmit(una); instanciaBd.SubmitChanges(); LimpiarCmapos(); Listar(); PanelAlerta.Visible = true; } catch (Exception) { pnlAlertaError.Visible = true; } }
private void Guardar() { pnlAlertaError.Visible = false; PanelAlerta.Visible = false; string nombre = txtNombrePersona.Text.Trim(); string apellido = txtApellido.Text.Trim(); string user = txtUsuario.Text.Trim(); string mail = txtCorreo.Text.Trim(); string contra = txtContrasena.Text.Trim(); int edad = int.Parse(txtEdad.Text); string saltAlgoritmoEncriptacion = encripto.GenerateSalt(); string contrasenaEncriptada = encripto.Compute(contra); persona.gsNombrePersona = nombre; persona.gsApellidoPersona = apellido; persona.gsEdad = edad; persona.gsEmail = mail; persona.gsUsuario = user; persona.gsPass = contrasenaEncriptada; persona.gsSalt = saltAlgoritmoEncriptacion; int resultado = persona.sp_CrearMensajero(); if (resultado > 0) { PanelAlerta.Visible = true; LimpiarCmapos(); Listar(); } else { pnlAlertaError.Visible = true; } }
public bool CheckPbkdf2Format(PasswordModel model) { var hashedPassword = _cryptoService.Compute(model.Password, model.SaltKey); return(_cryptoService.Compare(hashedPassword, model.HashedPassword)); }
public string Compute(string textToHash, string salt) { return(_simpleCrypto.Compute(textToHash, salt)); }
/// <summary> /// Generates a password hash /// </summary> public string GenerateHash(string password, string salt) { return(cryptoService.Compute(password, salt)); }
/// <summary> /// Hashes the password. /// </summary> /// <param name="password">The password.</param> /// <param name="salt">The salt.</param> /// <returns></returns> public string HashPassword(string password, string salt) { return(_cryptoServiceService.Compute(password, salt)); }