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)); }
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; } } } }
// оновлюємо пароль користувача 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); } } }
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")); }
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); } }
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); } }
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)); }
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)); }
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 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); }
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)); }
public CreateUserResponse Create(CreateUserRequest request) { var response = new CreateUserResponse(); try { crypto.HashIterations = 10; crypto.SaltSize = 12; var user = request.MapTo <User>(); user.Role = DataContext.RoleGroups.First(x => x.Id == request.RoleId); user.PasswordSalt = crypto.GenerateSalt(crypto.HashIterations, crypto.SaltSize); user.Password = crypto.Compute(request.Password, user.PasswordSalt); //user.Password = _pass.HashPassword(request.Password); DataContext.Users.Add(user); DataContext.SaveChanges(); if (request.RolePrivilegeIds.Count > 0) { user = DataContext.Users.Include(u => u.Role).Include(r => r.RolePrivileges).First(x => x.Id == user.Id).MapTo <User>(); user.RolePrivileges.Clear(); foreach (var role in request.RolePrivilegeIds) { var rolePrivilege = DataContext.RolePrivileges.Find(role).MapTo <RolePrivilege>(); user.RolePrivileges.Add(rolePrivilege); } DataContext.SaveChanges(); } response.IsSuccess = true; response.Message = "User item has been added successfully"; } catch (DbUpdateException dbUpdateException) { response.Message = dbUpdateException.Message; } return(response); }
public dynamic Execute(dynamic parameters, INancyModule module) { module.RequiresAuthentication(); IFeed feed; try { int feedId = int.Parse(parameters.id); feed = module.Bind <Feed>(); if (feedId != feed.Id) { return(HttpStatusCode.BadRequest); } ITransaction transaction = _store.BeginTransaction(); var existingFeedExists = transaction.Query <IFeed>().Where("Id = @feedId").Parameter("feedId", feedId).First(); if (existingFeedExists == null) { return(HttpStatusCode.NotFound); } if (!string.IsNullOrWhiteSpace(feed.ApiKey)) { ICryptoService cryptoService = new PBKDF2(); feed.ApiKeySalt = cryptoService.GenerateSalt(); feed.ApiKeyHashed = cryptoService.Compute(feed.ApiKey); } else if (feed.HasApiKey) { feed.ApiKeyHashed = existingFeedExists.ApiKeyHashed; //Temporary until API Key table is used feed.ApiKeySalt = existingFeedExists.ApiKeySalt; //Temporary until API Key table is used } transaction.Update(feed); transaction.Commit(); transaction.Dispose(); } catch (Exception ex) { return(HttpStatusCode.InternalServerError); } return(feed); }
public CreateUserResponse Create(CreateUserRequest request) { var response = new CreateUserResponse(); try { var user = request.MapTo <User>(); user.Role = DataContext.RoleGroups.First(x => x.Id == request.RoleId); user.PasswordSalt = crypto.GenerateSalt(crypto.HashIterations, crypto.SaltSize); user.Password = crypto.Compute(request.Password, user.PasswordSalt); //user.Password = _pass.HashPassword(request.Password); DataContext.Users.Add(user); DataContext.SaveChanges(); response.IsSuccess = true; response.Message = "User item has been added successfully"; } catch (DbUpdateException dbUpdateException) { response.Message = dbUpdateException.Message; } return(response); }
// <appSettings> // <add key = "correoElectronico" value="*****@*****.**"/> // <add key = "contraseniaCorreo" value="contra123"/> //</appSettings> protected void btnRecuperar_Click(object sender, EventArgs e) { int varCedula = Convert.ToInt32(cedula.Value.Trim()); List <Usuarios> allUsers = new List <Usuarios>(); allUsers = SIRESEP.BS.ManUsuario._Instancia.Mostrar(); int largo = Convert.ToInt32(allUsers.Count.ToString()); bool ok = false; for (int i = 0; i < largo; i++) { int cedulaForm = Convert.ToInt32(cedula.Value.Trim()); int cedulaBD = Convert.ToInt32(allUsers[i]._cedula.ToString()); if (cedulaForm == cedulaBD) { //Se hace nueva contraseña random y se manda al correo ICryptoService cryptoService = new PBKDF2(); string contraNueva = RandomPassword.Generate(10, PasswordGroup.Lowercase, PasswordGroup.Uppercase, PasswordGroup.Numeric); string salt = cryptoService.GenerateSalt(); string contraEncriptada = cryptoService.Compute(contraNueva); var query2 = (from a in SIRESEP.BS.ManUsuario._Instancia.Mostrar().AsEnumerable() where a._cedula == (cedula.Value) select a._correoElectronico); string correeo; correeo = query2.First().Trim(); //usuarioo = new Usuarios(); usuarioo = new Usuario(); usuarioo.correoElectronico = correeo; usuarioo.cedula = cedula.Value.Trim(); usuarioo.contrasena = contraEncriptada; usuarioo.salt = salt; SIRESEP.BS.ManUsuario._Instancia.ActualizarContra(usuarioo); EnviarEmail(usuarioo.correoElectronico, contraNueva); ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "AlertaUsuario", "window.onload = function(){ alert('Se ha enviado la nueva contrasenia al correo');};", true); } else { //Response.Redirect("FrLogin.aspx"); Response.Write("<script>window.location.href='FrLogin.aspx';</script>"); // ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "AlertaUsuario", "window.onload = function(){ alert('El usuario no existe');};", true); } } }
// Some testing here: Mono pictures are not rendered correctly, could be related to 'controls inside containers are rendered in reverse order' - more investigation required //public void DrawControl(Control control, Bitmap bitmap) //{ // control.DrawToBitmap(bitmap, control.Bounds); // foreach (Control childControl in control.Controls) // { // DrawControl(childControl, bitmap); // } //} private string PBKDF2_sk_string(string password, string sk) { int SALT_SIZE = 32; int HASH_ITERATIONS = 2000; ICryptoService cryptoService = new PBKDF2(); password.ToCharArray(); string salt = cryptoService.GenerateSalt(HASH_ITERATIONS, SALT_SIZE); string encrypted_sk = cryptoService.Compute(password, salt); return(encrypted_sk); }
protected void btnGuardar_Click(object sender, EventArgs e) { ICryptoService cryptoService = new PBKDF2(); //Algoritmo de encriptacion string salt = cryptoService.GenerateSalt(); string contraseniaencriptada = cryptoService.Compute(txtClave.Text); //fin del algoritmo clUsuarioE objUsuarioE = new clUsuarioE(); objUsuarioE.Documento = txtDocumento.Text; objUsuarioE.Nombre = txtNombre.Text; objUsuarioE.Apellido = txtApellido.Text; objUsuarioE.Telefono = txtTelefono.Text; objUsuarioE.Email = txtEmail.Text; objUsuarioE.Clave = txtClave.Text; objUsuarioE.Ciudad = txtCiudad.Text; objUsuarioE.Direccion = txtDireccion.Text; objUsuarioE.IdRol = int.Parse(cmbRol.SelectedValue.ToString()); clUsuario objUsuario = new clUsuario(); int resultsql = objUsuario.mtdRegistrarUsuario(objUsuarioE); if (resultsql > 0) { clCorreo objCorreo = new clCorreo(txtEmail.Text, "Registro Correcto!", "Registro Exitoso!"); if (objCorreo.Estado) { Response.Write("<script>alert('Registro exitoso del usuario.');window.location.href=''</script>"); } else { Response.Write("Erro al enviar <br>" + objCorreo.Mensaje_error); } //Limpiar Campos de texto txtDocumento.Text = ""; txtNombre.Text = ""; txtApellido.Text = ""; txtTelefono.Text = ""; txtEmail.Text = ""; txtClave.Text = ""; txtCiudad.Text = ""; txtDireccion.Text = ""; } }
public static Password Create(string plainTextPassword, int saltSize = 64) { if (string.IsNullOrWhiteSpace(plainTextPassword)) { throw new ArgumentException("Password should not be empty."); } if (saltSize < 16 || saltSize > 512) { throw new ArgumentOutOfRangeException("saltSize", saltSize, "Salt size should be between 16 and 512."); } var cryptoService = new PBKDF2(); var salt = cryptoService.GenerateSalt(HashIterations, saltSize); var hash = cryptoService.Compute(plainTextPassword, salt); return(new Password(hash, salt)); }
private void getValues(bool update) { label1.Visible = false; string varCedula = cedula.Value.Trim(); string varcorreo = inputEmail.Value.Trim(); string contra = inputPassword.Value.Trim(); string contraConfirm = confirmPassword.Value.Trim(); //var contraescriptada = confirmPassword.Value = Encriptacion.Encriptar(confirmPassword.Value.Trim(), Encriptacion.Llave); ICryptoService cryptoService = new PBKDF2(); //el salt es el algoritmo de encriptacion string saltt = cryptoService.GenerateSalt(); string contraseniaEncriptada = cryptoService.Compute(contra); string contrr = contraseniaEncriptada; int rolInsert; if (Helping == 1) { rolInsert = 1; } else { rolInsert = 2; } if (contra == contraConfirm) { usuario = new Usuarios(); if (update) { usuario._cedula = varCedula; } usuario._cedula = varCedula; usuario._correoElectronico = varcorreo; usuario._contrasena = contrr; usuario._idRol = rolInsert; usuario._salt = saltt; validacion = true; } else { label1.Visible = true; validacion = false; } }
public User ChangePassword(int userId, string password) { using (TransactionScope scope = new TransactionScope()) { var user = _context.Users.SingleOrDefault(m => m.Id == userId); if (user == null) { return(null); } ICryptoService cryptoService = new PBKDF2(); string passwordSalt = cryptoService.GenerateSalt(); string hashedPassword = cryptoService.Compute(password); user.Password = hashedPassword; user.PasswordSalt = passwordSalt; _context.SaveChanges(); scope.Complete(); return(user); } }
public ActionResult Recuperar(string correo, string password) { string constr = conexion; 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()) { if (sdr.HasRows) { ICryptoService cryptoService = new PBKDF2(); Salt = cryptoService.GenerateSalt(); PasswordEncriptada = cryptoService.Compute(password); string constr1 = conexion; using (MySqlConnection Con1 = new MySqlConnection(constr1)) { Con1.Open(); MySqlCommand cmd1 = new MySqlCommand(bd + "web_actualiza_password", Con1); cmd1.CommandType = CommandType.StoredProcedure; cmd1.Parameters.AddWithValue("p_usuario", correo); cmd1.Parameters.AddWithValue("p_clave", PasswordEncriptada); cmd1.Parameters.AddWithValue("p_salt", Salt); cmd1.Parameters.AddWithValue("p_Password_Dsk", password); cmd1.ExecuteNonQuery(); Con1.Close(); } } } } con.Close(); } } return(RedirectToAction("../Login/Login")); }
private static void HashPasswordFromTestPBKDF(string passwordToHash, int numberOfIterations) { var sw = new Stopwatch(); sw.Start(); var hashedPassword = PBKDF2.HashPasswordWithPBKDF( Encoding.UTF8.GetBytes(passwordToHash), PBKDF2.GenerateSalt(), numberOfIterations ); sw.Stop(); Console.WriteLine(); Console.WriteLine($"Password to hash: {passwordToHash}"); Console.WriteLine($"Hashed Password: {Convert.ToBase64String(hashedPassword)}"); Console.WriteLine($"Iterations <{numberOfIterations}> | Elapsed Time: {sw.ElapsedMilliseconds}"); }
protected void btnGuardar_Click(object sender, EventArgs e) { try { string nombre = txtNombrePersona.Text.Trim(); string apellidos = txtApellidos.Text.Trim(); string usuario = txtUsuario.Text.Trim(); string contrasenna = txtContrasenna.Text.Trim(); int edad = int.Parse(txtEdad.Text.Trim()); string email = txtEmail.Text.Trim(); ICryptoService cryptoService = new PBKDF2(); string salt = cryptoService.GenerateSalt(); string contrasenaEncriptada = cryptoService.Compute(contrasenna); Persona objPersona = new Persona(); objPersona.nombrePersona = nombre; objPersona.apellidoPersona = apellidos; objPersona.usuario = usuario; objPersona.contrasenna = contrasenaEncriptada; objPersona.edad = edad; objPersona.salt = salt; objPersona.estado = 1; objPersona.idTipoPersona = 2; objPersona.email = email; try { db.Persona.InsertOnSubmit(objPersona); db.SubmitChanges(); } catch (Exception) { throw; } } catch { ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "alertaPassFail", "window.onload = function(){alert('Debe rellenar la solicitud');};", true); } }
public bool SalvaRegistrazione(ControllerContext controller, DatabaseContext db) { CONTO_CORRENTE conto = db.CONTO_CORRENTE.Create(); conto.ID = Guid.NewGuid(); conto.TOKEN = Guid.NewGuid(); conto.DATA_INSERIMENTO = DateTime.Now; conto.STATO = (int)Stato.ATTIVO; db.CONTO_CORRENTE.Add(conto); db.SaveChanges(); PBKDF2 crypto = new PBKDF2(); PERSONA persona = db.PERSONA.Create(); persona.TOKEN = Guid.NewGuid(); persona.TOKEN_PASSWORD = crypto.GenerateSalt(1, 20); persona.PASSWORD = crypto.Compute(this.Password.Trim(), persona.TOKEN_PASSWORD); //persona.NOME = this.Nome.Trim(); //persona.COGNOME = this.Cognome.Trim(); persona.ID_CONTO_CORRENTE = conto.ID; persona.ID_ABBONAMENTO = db.ABBONAMENTO.SingleOrDefault(item => item.NOME == "BASE").ID; persona.DATA_INSERIMENTO = DateTime.Now; persona.STATO = (int)Stato.INATTIVO; db.PERSONA.Add(persona); if (db.SaveChanges() > 0) { PERSONA_EMAIL personaEmail = db.PERSONA_EMAIL.Create(); personaEmail.ID_PERSONA = persona.ID; personaEmail.EMAIL = this.Email.Trim(); personaEmail.TIPO = (int)TipoEmail.Registrazione; personaEmail.DATA_INSERIMENTO = DateTime.Now; personaEmail.STATO = (int)Stato.INATTIVO; db.PERSONA_EMAIL.Add(personaEmail); if (db.SaveChanges() > 0) { InvioEmail(controller, persona, personaEmail); return(true); } } return(false); }
public JsonResult GuardarUsuarioLogin(List <Usuarios> dataToProcess) { Usuarios Usuario = new Usuarios(); foreach (var item in dataToProcess) { Usuario.Cod_Usuario = item.Cod_Usuario; Usuario.Nombre = item.Nombre; Usuario.Apellido = item.Apellido; Usuario.Rut = item.Rut; Usuario.Cod_Perfil = item.Cod_Perfil; Usuario.Password = item.Password; Usuario.Salt = item.Salt; Usuario.User_Log = item.User_Log; ICryptoService cryptoService = new PBKDF2(); Salt = cryptoService.GenerateSalt(); PasswordEncriptada = cryptoService.Compute(Usuario.Password); //LLENADO DE BD string constr = conexion; using (MySqlConnection con = new MySqlConnection(constr)) { con.Open(); MySqlCommand cmd = new MySqlCommand(bd + "web_pingresa_usuarios_login", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("p_Cod_Usuario", Usuario.Cod_Usuario); cmd.Parameters.AddWithValue("p_Nombre", Usuario.Nombre); cmd.Parameters.AddWithValue("p_Apellido", Usuario.Apellido); cmd.Parameters.AddWithValue("p_Rut", Usuario.Rut); cmd.Parameters.AddWithValue("p_Cod_Perfil", Usuario.Cod_Perfil); cmd.Parameters.AddWithValue("p_Password", PasswordEncriptada); cmd.Parameters.AddWithValue("p_salt", Salt); cmd.Parameters.AddWithValue("p_User_Log", Usuario.User_Log); cmd.Parameters.AddWithValue("p_Password_Dsk", Usuario.Password); cmd.ExecuteNonQuery(); con.Close(); } } return(Json(dataToProcess, JsonRequestBehavior.AllowGet)); }
protected void btnRegistrar_Click(object sender, EventArgs e) { ICryptoService cryptoService = new PBKDF2(); //Algoritmo de encriptacion string salt = cryptoService.GenerateSalt(); string contraseniaencriptada = cryptoService.Compute(txtPasswordR.Text); //fin del algoritmo //Clase RegistroUE con objetos clRegistroUE objLoginE = new clRegistroUE(); objLoginE.Documento = int.Parse(txtDocumentoR.Text); objLoginE.Nombre = txtNombreR.Text; objLoginE.Email = txtCorreoR.Text; objLoginE.Telefono = txtTelefonoR.Text; objLoginE.Clave = txtPasswordR.Text; //Debe tomar el txt a su vez. //Metodo clRegistroU objLogin = new clRegistroU(); int resultsql = objLogin.mtdRegistrarUsuarioLogin(objLoginE); if (resultsql > 0) { //Envio de correo clCorreo objCorreo = new clCorreo(txtCorreoR.Text, "Registro Correcto!", "Registro Exitoso!"); if (objCorreo.Estado) { Response.Write("<script>alert('Registro Exitoso!');window.location.href='Login.aspx'</script>"); } else { Response.Write("<script>alert('Error al registrar datos');window.location.href='Login.aspx'</script>"); Response.Write("Erro al enviar <br>" + objCorreo.Mensaje_error); } //enviar mensaje Response.Write("<script>alert('Registro Completado! :D');window.location.href='Login.aspx'</script>"); } }
public ActionResult ResetPassword(string oldPassword, string newPassword, string email) { //check if old password matches var user = db.Employees.FirstOrDefault(e => e.EmployeeEmail == email); if (user != null) { ICryptoService cryptoService = new PBKDF2(); string hashed = cryptoService.Compute(oldPassword, user.Salt); if (hashed == user.Pass) //if the old password is correct { //generate a new salt string salt = cryptoService.GenerateSalt(); user.Salt = salt; //hash new password string hashedPassword = cryptoService.Compute(newPassword); user.Pass = hashedPassword; db.SaveChanges(); //log the user in Session["userLoggedIn"] = user.EmployeeEmail; return(RedirectToAction("Index", "Interviews")); } else { ViewBag.message = "Old password is incorrect, please try again"; return(View()); } } else { ViewBag.message = "No user with that email address exists, please try again"; return(View()); } }
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity <Booking>(builder => { builder.Property(x => x.Id).IsRequired().Metadata.IsPrimaryKey(); builder.Property(x => x.BookingDateTime).IsRequired(); builder.Property(x => x.Flexibility).IsRequired(); builder.Property(x => x.VehicleSize).IsRequired(); builder.Property(x => x.Name).IsRequired(); builder.Property(x => x.ContactNumber).IsRequired(); builder.Property(x => x.EmailAddress).IsRequired(); builder.Property(x => x.Approved).IsRequired(); }); var creation = DateTime.UtcNow; var cryptoService = new PBKDF2(); var salt = cryptoService.GenerateSalt(); string hashedPassword = cryptoService.Compute("l7iM007iD9o", salt); modelBuilder.Entity <User>(builder => { builder.Property(x => x.Id).IsRequired().Metadata.IsPrimaryKey(); builder.Property(x => x.UserName).IsRequired(); builder.Property(x => x.Password).IsRequired(); builder.HasData(new User { Id = 1, UserName = "******", Password = hashedPassword, Salt = salt, CreatedAt = creation, UpdatedAt = creation }); }); }
//METODO DE GUARDAR USUARIO protected void txtGuardar_Click(object sender, EventArgs e) { int cedulaUsuario = int.Parse(txtcedulaUsuario.Text.Trim()); string correoElectronico = txtnombreCompleto.Text.Trim(); int idRol = int.Parse(txtRol.Text.Trim()); string contrasenia = txtcontrasenna.Text.Trim(); //Para encriptar protocolo ICryptoService cryptoService = new PBKDF2(); //Generar algoritmo de encriptación string salt = cryptoService.GenerateSalt(); string contraseniaEncriptada = cryptoService.Compute(contrasenia); ModelPersona usuario = new ModelPersona(); usuario.cedulaAsociado = cedulaUsuario; usuario.correoElectronico = correoElectronico; usuario.idRol = idRol; usuario.contrasenna = contraseniaEncriptada; usuario.salt = salt; usuario.idEstadoDatos = 1; int resultado = usuario.CrearUsuario(); if (resultado == 1) { ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "alertaExito", "window.onload = function() { alert('Mensajero registrado exitosamente.'); }", true); } else { ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "alertaError", "window.onload = function() { alert('Opps!! Ocurrio un error al registrar el usuario.'); }", true); } }
public bool SalvaRegistrazione(ControllerContext controller, DatabaseContext db) { CONTO_CORRENTE conto = db.CONTO_CORRENTE.Create(); conto.ID = Guid.NewGuid(); conto.TOKEN = Guid.NewGuid(); conto.DATA_INSERIMENTO = DateTime.Now; conto.STATO = (int)Stato.ATTIVO; db.CONTO_CORRENTE.Add(conto); db.SaveChanges(); PBKDF2 crypto = new PBKDF2(); PERSONA persona = db.PERSONA.Create(); persona.TOKEN = Guid.NewGuid(); persona.TOKEN_PASSWORD = crypto.GenerateSalt(1, 20); persona.PASSWORD = crypto.Compute(this.Password.Trim(), persona.TOKEN_PASSWORD); persona.ID_CONTO_CORRENTE = conto.ID; persona.ID_ABBONAMENTO = db.ABBONAMENTO.SingleOrDefault(item => item.NOME == "BASE").ID; persona.DATA_INSERIMENTO = DateTime.Now; persona.STATO = (int)Stato.INATTIVO; // solo in caso di accesso con FB persona.FACEBOOK_TOKEN_SESSIONE = FacebookToken; persona.FACEBOOK_TOKEN_PERMANENTE = FacebookTokenPermanente; if (!string.IsNullOrWhiteSpace(this.Nome)) { persona.NOME = this.Nome.Trim(); } if (!string.IsNullOrWhiteSpace(this.Cognome)) { persona.COGNOME = this.Cognome.Trim(); } db.PERSONA.Add(persona); if (db.SaveChanges() > 0) { PERSONA_EMAIL personaEmail = db.PERSONA_EMAIL.Create(); personaEmail.ID_PERSONA = persona.ID; personaEmail.EMAIL = this.Email.Trim(); personaEmail.TIPO = (int)TipoEmail.Registrazione; personaEmail.DATA_INSERIMENTO = DateTime.Now; personaEmail.STATO = (int)Stato.INATTIVO; db.PERSONA_EMAIL.Add(personaEmail); if (db.SaveChanges() > 0) { PersonaModel utente = new PersonaModel(persona); // assegna bonus canale pubblicitario if (HttpContext.Current.Request.Cookies.Get("GXG_promo") != null) { string promo = HttpContext.Current.Request.Cookies.Get("GXG_promo").Value; utente.AddBonusCanalePubblicitario(db, promo); // reset cookie HttpCookie currentUserCookie = HttpContext.Current.Request.Cookies["GXG_promo"]; if (currentUserCookie != null) { HttpContext.Current.Response.Cookies.Remove("GXG_promo"); currentUserCookie.Expires = DateTime.Now.AddDays(-10); currentUserCookie.Value = null; HttpContext.Current.Response.SetCookie(currentUserCookie); } } InvioEmail(controller, persona, personaEmail); return(true); } } return(false); }