protected void btnRegister_Click(object sender, EventArgs e) { try { BookReviewDbEntities db = new BookReviewDbEntities(); RandomSeed rs = new RandomSeed(); int seed = rs.GetSeed(); PasswordHash ph = new PasswordHash(); Byte[] hashed = ph.HashIt(txtPassword.Text, seed.ToString()); Reviewer rev = new Reviewer(); rev.ReviewerFirstName = txtFirstName.Text; rev.ReviewerUserName = txtUserName.Text; rev.ReviewerLastName = txtLastName.Text; rev.ReviewerEmail = txtEmail.Text; rev.ReviewerDateEntered = DateTime.Now; rev.ReviewPlainPassword = txtPassword.Text; rev.ReviewerKeyCode = seed; rev.ReviewerHashedPass = hashed; db.Reviewers.Add(rev); db.SaveChanges(); lblErrorSuccess.Text = "Reviewer Saved"; } catch(Exception ex) { lblErrorSuccess.Text = ex.Message; } }
public int ValidateLogin() { //personKey to return, initially 0 int pk = 0; //LINQ to extract personkeyt, passcode, and hashedpassword var log = from r in ae.People where r.PersonUsername == username && r.PersonPlainPassword == password select new { r.PersonKey, r.Personpasskey, r.PersonUserPassword }; int pCode = 0; Byte[] pWord; int personKey = 0; //loop through results and assign values from the var log to our variables foreach (var p in log) { pk = (int)p.PersonKey; pCode = (int)p.Personpasskey; pWord = (Byte[])p.PersonUserPassword; } //initial the passWordHash PasswordHash ph = new PasswordHash(); Byte[] newHash = ph.HashIt(password, pCode.ToString()); // string passString = ConvertBytes(pWord); // string newHashString = ConvertBytes(newHash); // if (passString.Equals(newHash)) // { pk = personKey; // } return pk; }
public void Register(Person p, PersonAddress pa) { PasswordHash phash = new PasswordHash(); KeyCode keycode = new KeyCode(); int key = keycode.GetKeyCode(); byte[] hash = phash.HashIt(p.PersonPlainPassword, key.ToString()); Person person = new Person(); person.PersonFirstName = p.PersonFirstName; person.PersonLastName = p.PersonLastName; person.Personpasskey = key; person.PersonUsername = p.PersonUsername; person.PersonPlainPassword = p.PersonPlainPassword; person.PersonUserPassword = hash; person.PersonEntryDate = DateTime.Now; communityAssistDb.People.Add(person); PersonAddress pAddress = new PersonAddress(); pAddress.Person = person; pAddress.Apartment = pa.Apartment; pAddress.Street = pa.Street; pAddress.City = pa.City; pAddress.State = pa.State; pAddress.Zip = pa.Zip; communityAssistDb.PersonAddresses.Add(pAddress); communityAssistDb.SaveChanges(); }
public void valid_pwd_existing_hash() { var hash = new PasswordHash(Password,Salt.Generate()).ToString(); var sut = PasswordHash.FromHash(hash); sut.IsValidPassword(Password).Should().BeTrue(); sut.IsValidPassword("-" + Password).Should().BeFalse(); }
protected void btnSubmit_Click(object sender, EventArgs e) { PassCodeGenerator pg = new PassCodeGenerator(); int passcode = pg.GetPasscode(); Customer c = new Customer(); Donation d = new Donation(); PasswordHash ph = new PasswordHash(); c.LastName = txtLastName.Text; c.FirstName = txtFirstName.Text; c.Email = txtEmail.Text; c.Password = txtPassword.Text; //c.passcode = passcode; //c.PasswordHash = ph.HashIt(txtPassword.Text, passcode.ToString()); try { ManagePerson mp = new ManagePerson(d, c); mp.WriteRegisteredCustomer(); mp.WriteDonation(); lblResult.Text = "Thank you for registering!"; LinkButton1.Visible = true; } catch (Exception ex) { lblResult.Text = ex.ToString(); } }
public int ValidateLogin(string user, string pass) { int result = 0; PasswordHash ph = new PasswordHash(); string sql = "Select PersonKey, CustomerPassCode, CustomerHashedPAssword " + "From Customer.RegisteredCustomer Where Email = @User"; SqlCommand cmd = new SqlCommand(sql, connect); cmd.Parameters.Add("@User", user); SqlDataReader reader; int passCode = 0; Byte[] originalPassword = null; int personKey = 0; connect.Open(); reader = cmd.ExecuteReader(); if (reader.HasRows) { passCode = (int)reader["CustomerPassCode"]; originalPassword = (Byte[])reader["CustomerHashedPassword"]; personKey = (int)reader["PersonKey"]; } byte[] newhash = ph.HashIt(pass, passCode.ToString()); if(newhash.SequenceEqual(originalPassword)) { result = personKey; } else { result = 0; } return result; }
protected void btnSubmit_Click(object sender, EventArgs e) { AutomartEntities ae = new AutomartEntities(); Person p = new Person(); p.LastName = txtLastName.Text; p.FirstName = txtFirstName.Text; ae.People.Add(p); vehicle v = new vehicle(); v.Person = p; v.VehicleMake = txtMake.Text; v.LicenseNumber = txtLicense.Text; v.VehicleYear = ddYears.SelectedItem.ToString(); ae.vehicles.Add(v); Random rand = new Random(); int passcode = rand.Next(1000000, 9999999); PasswordHash ph = new PasswordHash(); byte[] hashed = ph.HashIt(txtPassword.Text, passcode.ToString()); RegisteredCustomer rc = new RegisteredCustomer(); rc.Person = p; rc.Email = txtEmail.Text; rc.CustomerPassCode = passcode; rc.CustomerPassword = txtPassword.Text; rc.CustomerHashedPassword = hashed; ae.RegisteredCustomers.Add(rc); ae.SaveChanges(); }
public void WriteCustomer(Customer c) { string sqlPerson = "Insert into Person (LastName, FirstName) Values (@LastName, @FirstName)"; string sqlVehicle = "Insert into Customer.Vehicle (LicenseNumber, VehicleMake, VehicleYear, PersonKey) " + "Values(@License, @Make, @Year, ident_Current('Person'))"; string sqlRegisteredCustomer = "Insert into Customer.RegisteredCustomer(Email, CustomerPasscode, " + "CustomerPassword, CustomerHashedPassword, PersonKey) " + "Values(@Email, @Passcode, @password, @hashedpass, ident_Current('Person'))"; SqlCommand personCmd = new SqlCommand(sqlPerson, connect); personCmd.Parameters.AddWithValue("@LastName", c.LastName); personCmd.Parameters.AddWithValue("@FirstName", c.FirstName); SqlCommand vehicleCmd = new SqlCommand(sqlVehicle, connect); vehicleCmd.Parameters.AddWithValue("@License", c.LicenseNumber); vehicleCmd.Parameters.AddWithValue("@Make", c.VehicleMake); vehicleCmd.Parameters.AddWithValue("@Year", c.VehicleYear); PasscodeGenerator pg = new PasscodeGenerator(); PasswordHash ph = new PasswordHash(); int passcode = pg.GetHashCode(); SqlCommand regCustomerCmd = new SqlCommand(sqlRegisteredCustomer, connect); regCustomerCmd.Parameters.AddWithValue("@Email", c.Email); regCustomerCmd.Parameters.AddWithValue("@Passcode", passcode); regCustomerCmd.Parameters.AddWithValue("@Password", c.PlainPassword); regCustomerCmd.Parameters.AddWithValue("@hashedPass", ph.HashIt(c.PlainPassword, passcode.ToString())); connect.Open(); personCmd.ExecuteNonQuery(); vehicleCmd.ExecuteNonQuery(); regCustomerCmd.ExecuteNonQuery(); connect.Close(); }
public void equatable_test() { var p1 = new PasswordHash(Password,PasswordHash.DefaultIterations ,_salt); var p3 = new PasswordHash(Password, PasswordHash.DefaultIterations, Salt.Generate(PasswordHash.DefaultSaltSize)); p1.Equals(_sut).Should().BeTrue(); p1.Equals(p3).Should().BeFalse(); }
/// <summary> /// Generates a hash for the given plain text value and returns a /// base64-encoded result. Before the hash is computed, a random salt /// is generated and appended to the plain text. This salt is stored at /// the end of the hash value, so it can be used later for hash /// verification. /// </summary> /// <param name="plainText">Plaintext value to be hashed. The function does not check whether this parameter is null.</param> /// <param name="mode">Password encryption mode.</param> /// <returns> /// Password hash and salt. /// </returns> public static PasswordHash Encrypt(String plainText, PasswordMode mode) { PasswordHash result; if (hashAlgorithmMapping.ContainsKey(mode)) { HashAlgorithm algorithm = hashAlgorithmMapping[mode]; var saltBytes = new byte[SaltLength]; RandomNumberGenerator.Create().GetBytes(saltBytes); var passwordBytes = Encoding.UTF8.GetBytes(plainText); var hashBytes = Encrypt(passwordBytes, saltBytes, algorithm); result = new PasswordHash { Salt = Convert.ToBase64String(saltBytes), Hash = Convert.ToBase64String(hashBytes) }; } else { result = new PasswordHash { Salt = String.Empty, Hash = plainText }; } return result; }
public int ValidateLogin() { //personkey to return initally 0 int pk = 0; //LINQ to extract personkey, passcode and hash from database var log = from p in ca.People where p.PersonUsername == userName && p.PersonPlainPassword == password select new { p.PersonKey, p.Personpasskey, p.PersonUserPassword}; //variables to store results from database int pCode = 0; Byte[] pWord = null; int personKey = 0; //loop throug results and assign values from var log //to our variables foreach (var s in log) { personKey = (int)s.PersonKey; pCode = (int)s.Personpasskey; pWord = (Byte[])s.PersonUserPassword; } //initial the PassWordHash PasswordHash ph = new PasswordHash(); //send password and passcode to be hashed Byte[] newHash = ph.HashIt(password, pCode.ToString()); if (pWord.SequenceEqual(newHash)) { pk = personKey; } return pk; }
public int ValidateLogin() { int pk = 0;//personkey to return intially 0 var log = from r in ae.People//linq to extract personkey, passcode and hass form database where r.PersonUsername == userName && r.PersonPlainPassword == password select new { r.PersonKey, r.Personpasskey, r.PersonUserPassword }; int pCode = 0;//variables to store results from database Byte[] pWord = null; int personKey = 0; foreach (var p in log)//loop through results and assign values from var log { personKey = (int)p.PersonKey; pCode = (int)p.Personpasskey; pWord = (Byte[])p.PersonUserPassword; } PasswordHash ph = new PasswordHash();//intitial the password hash Byte[] newHash = ph.HashIt(password, pCode.ToString());//send password and passcode to be hashed if (pWord.SequenceEqual(newHash)) { pk = personKey; } return pk; }
public int ValidateLogin() { int pk = 0; var log = from r in ce.People where r.PersonUsername == username && r.PersonPlainPassword == password select new { r.PersonKey, r.Personpasskey, r.PersonUserPassword }; int pCode = 0; Byte[] pWord=null; //int pk = 0; int personkey=0; foreach (var p in log) { personkey = (int)p.PersonKey; pCode = (int)p.Personpasskey; pWord = (Byte[])p.PersonUserPassword; } PasswordHash ph = new PasswordHash(); Byte[] newHash = ph.Hashit(password, pCode.ToString()); //string passString = ConvertBytes(pWord); //string newHashString = ConvertBytes(newHash); if (pWord.SequenceEqual(newHash)) { pk = personkey; } // if (passString.Equals(newHashString)) // { // pk = personkey; // } return pk; }
public void WriteCustomer(Customer c) { string sqlPerson = "Insert into Person(PersonLastName, PersonFirstName,PersonUserName,PersonPlainPassword,Personpasskey,PersonUserPassword,PersonEntryDate) Values(@LastName, @FirstName, @UserName, @PlainPassword, @Passcode, @HashedPassword, @EntryDate)"; string sqlPersonAddress = "Insert into PersonAddress(Street, Apartment, City, State, Zip, Personkey) " + "Values(@Street, @Apartment, @City, @State, @Zip, ident_Current('Person'))"; PasscodeGenerator pg = new PasscodeGenerator(); PasswordHash ph = new PasswordHash(); int Passcode = pg.GetPasscode(); SqlCommand personCmd = new SqlCommand(sqlPerson, connect); personCmd.Parameters.AddWithValue("@FirstName", c.FirstName); personCmd.Parameters.AddWithValue("@LastName", c.LastName); personCmd.Parameters.AddWithValue("@UserName", c.Email); personCmd.Parameters.AddWithValue("@PlainPassword", c.PlainPassword); personCmd.Parameters.AddWithValue("@Passcode", Passcode); personCmd.Parameters.AddWithValue("@HashedPassword", ph.HashIt(c.PlainPassword.ToString(), Passcode.ToString())); personCmd.Parameters.AddWithValue("@EntryDate", DateTime.Now); SqlCommand addressCmd = new SqlCommand(sqlPersonAddress, connect); addressCmd.Parameters.AddWithValue("@Street", c.Street); addressCmd.Parameters.AddWithValue("@Apartment", c.Apartment); addressCmd.Parameters.AddWithValue("@City", c.City); addressCmd.Parameters.AddWithValue("@State", c.State); addressCmd.Parameters.AddWithValue("@Zip", c.Zip); connect.Open(); personCmd.ExecuteNonQuery(); addressCmd.ExecuteNonQuery(); connect.Close(); }
public int ValidateLogin(string user, string pass) { int result = 0; PasswordHash ph = new PasswordHash(); string sql = "Select PersonKey, Personpasskey, PersonUserPassword " + "From Person Where PersonUsername = @User"; SqlCommand cmd = new SqlCommand(sql, connect); cmd.Parameters.Add("@User", user); SqlDataReader reader; int passCode = 0; Byte[] originalPassword = null; int personKey = 0; connect.Open(); reader = cmd.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { passCode = (int)reader["Personpasskey"]; originalPassword = (byte[])reader["PersonUserPassword"]; personKey = (int)reader["PersonKey"]; } } byte[] newhash = ph.HashIt(pass, passCode.ToString()); if (newhash.SequenceEqual(originalPassword)) { result = personKey; } connect.Close(); return result; }
public void valid_password() { var sut = new PasswordHash(Password,Salt.Generate()); sut.IsValidPassword(Password).Should().BeTrue(); sut.IsValidPassword(Password + "f").Should().BeFalse(); Console.WriteLine(sut.ToString()); Console.Write(sut.ToString().Length); }
public void hash_from_array() { var hash2 = new PasswordHash(_sut.Hash, _sut.Salt.Length,PasswordHash.DefaultIterations); hash2.Hash.Should().BeEquivalentTo(_sut.Hash); hash2.IsValidPassword(Password).Should().BeTrue(); }
public int ValidateLogin() { //set the personID to 0 int personID = 0; //create the SQL String string sql = "Select PersonKey, Personpasskey, PersonUserPassword from Person " + "Where Personusername=@email and PersonPlainPassword=@password"; //create the command object SqlCommand cmd = new SqlCommand(sql, connect); cmd.Parameters.AddWithValue("@email", username); cmd.Parameters.AddWithValue("@password", password); //set up the hash PasswordHash ph = new PasswordHash(); Byte[] hashed; SqlDataReader reader = null; int passcode; //open the connection connect.Open(); // If it crashes here, it means connectionString or SQL statement is wrong //execute the reader reader = cmd.ExecuteReader(); //loop through the records while (reader.Read()) { //if there is something there if (reader["Personpasskey"] != null) { //retrieve the passcode passcode = (int)reader["Personpasskey"]; //rehash it with the user name hashed = ph.Hashit(password, passcode.ToString()); //for comparison purposes I am converting the Byte array to a string string passHash = ConvertBytes(hashed); //if it matches assign it to the personID Byte[] savedPass = (Byte[])reader["PersonUserPassword"]; //also converting to a string string savedHash = ConvertBytes(savedPass); //if they match return the person key if (passHash.Equals(savedHash)) { personID = (int)reader["PersonKey"]; break; //exit the while } } } reader.Close(); connect.Close(); //return the person id return personID; }
public void equatable_test() { var salt = Salt.Generate(); var p1 = new PasswordHash(Password, salt); var p2 = new PasswordHash(Password, salt); var p3 = new PasswordHash(Password, Salt.Generate()); p1.Equals(p2).Should().BeTrue(); p1.Equals(p3).Should().BeFalse(); }
public void hash_from_array() { var hash = new PasswordHash(Password, Salt.Generate()); var bytes = hash.Hash; var hash2 = new PasswordHash(bytes); hash2.Should().Be(hash); hash.ToString().ToConsole(); hash2.ToString().ToConsole(); }
public bool ValidateUser(string username, PasswordHash passwordHash) { try { var user = Store.Administrators.Get(username); return user != null && user.Status == EntityStatus.Enabled && user.PasswordHash == passwordHash; } catch (Exception ex) { throw CreateFault("Authenticate", ex); } }
protected void btnSubmit_Click(object sender, EventArgs e) { //get the passcode PasscodeGenerator pg = new PasscodeGenerator(); int passcode = pg.GetPasscode(); //initialize customer and vehicle Customer c = new Customer(); Vehicle v = new Vehicle(); //initialize PasswordHash PasswordHash ph = new PasswordHash(); //Assign the values from the textboxes //to the classes c.LastName = txtLastName.Text; c.FirstName = txtFirstName.Text; c.email = txtEmail.Text; c.password = txtPassword.Text; c.passcode = passcode; //get the hashed password c.PasswordHash = ph.Hashit(txtPassword.Text, passcode.ToString()); c.apartment = txtApt.Text; c.state = txtState.Text; c.street = txtStreet.Text; c.zip = txtZip.Text; c.city = txtCity.Text; c.phone = txtPhone.Text; // v.License = txtLicense.Text; //v.Make = txtMake.Text; // v.Year = txtYear.Text; try { //try to write to the database Registrations r = new Registrations(c); lblResult.Text = "Thank you for registering"; LinkButton1.Visible = true; } catch (Exception ex) { //if it fails show the error lblError.Text = ex.ToString(); } }
protected void btnSubmit_Click(object sender, EventArgs e) { try { CommunityAssistEntities ce = new CommunityAssistEntities(); Person p = new Person(); p.PersonFirstName = txtFirstName.Text; p.PersonLastName = txtLastName.Text; p.PersonUsername = txtEmail.Text; p.PersonPlainPassword = txtConfirm.Text; PasscodeGenerator pg = new PasscodeGenerator(); int passcode = pg.GetPasscode(); PasswordHash ph = new PasswordHash(); p.Personpasskey = passcode; p.PersonUserPassword = ph.Hashit(txtConfirm.Text, passcode.ToString()); ce.People.Add(p); //vehicle v = new vehicle(); //v.LicenseNumber = txtLicense.Text; //v.VehicleMake = txtMake.Text; //v.VehicleYear = ddYear.SelectedItem.ToString(); //v.Person = p; //ce.vehicles.Add(v); //PasscodeGenerator pg = new PasscodeGenerator(); //int passcode = pg.GetPasscode(); //PasswordHash ph = new PasswordHash(); //RegisteredCustomer rc = new RegisteredCustomer(); //rc.Person = p; //rc.Email = txtEmail.Text; //rc.CustomerPassCode = passcode; //rc.CustomerPassword = txtConfirm.Text; //rc.CustomerHashedPassword = ph.Hashit(txtConfirm.Text, passcode.ToString()); //ce.Person.Add(p); ce.SaveChanges(); Response.Redirect("Welcome.aspx"); } catch (Exception ex) { lblResult.Text = ex.Message; } }
private SqlCommand WriteRegisteredCustomer() { PasscodeGenerator pg = new PasscodeGenerator(); PasswordHash ph = new PasswordHash(); int passcode = pg.GetPasscode(); string sqlRegisteredCustomer = "Insert into Customer.RegisteredCustomer(Email, Passcode, CustomerPassword, CustomerHashedPassword, PErsonKey) " + "Values(@Email, @Passcode, @Password, @Hashedpass, identCurrent('Person'))"; SqlCommand regCustomerCmd = new SqlCommand(sqlRegisteredCustomer, connect); regCustomerCmd.Parameters.AddWithValue("@Email", c.Email); regCustomerCmd.Parameters.AddWithValue("@Passcode", pg.GetPasscode()); regCustomerCmd.Parameters.AddWithValue("@Password", c.Password); regCustomerCmd.Parameters.AddWithValue("@hashedPass", ph.HashIt(c.Password.ToString(), passcode.ToString())); return regCustomerCmd; }
public void see_it_in_action() { var hash = new PasswordHash(); var password = "******"; for (int i = 0; i < 50; i++) { Debug.WriteLine(hash.CreateHash(password)); } hash.CreateHash(password).ShouldEqual(hash.CreateHash(password)); hash.CreateHash(password).ShouldEqual(hash.CreateHash(password)); hash.CreateHash(password).ShouldEqual(hash.CreateHash(password)); hash.CreateHash(password).ShouldEqual(hash.CreateHash(password)); hash.CreateHash(password).ShouldNotEqual(password); }
//public void WritePerson() //{ // string sql = "Insert into Person() Values ()"; // SqlCommand cmd = new SqlCommand(sql, connect); // connect.Open(); // cmd.ExecuteNonQuery(); // connect.Close(); //} public void WriteRegisteredCustomer() { string sql = "Insert into Person(PersonLastName, PersonFirstName, PersonUsername, PersonPlainPassword, Personpasskey, PersonUserPassword, PersonEntryDate ) Values (@Last,@First, @Email,@Password, @Passcode, @hash, GetDate())"; PassCodeGenerator psg = new PassCodeGenerator(); int passcode = psg.GetPasscode(); PasswordHash ph = new PasswordHash(); SqlCommand cmd = new SqlCommand(sql, connect); cmd.Parameters.AddWithValue("@Last", c.LastName); cmd.Parameters.AddWithValue("@First", c.FirstName); cmd.Parameters.AddWithValue("@Email", c.Email); cmd.Parameters.AddWithValue("@Password", c.Password); cmd.Parameters.AddWithValue("@PassCode", passcode); cmd.Parameters.AddWithValue("@hash", ph.HashIt(c.Password, passcode.ToString())); connect.Open(); cmd.ExecuteNonQuery(); connect.Close(); }
public int ValidateLogin() { int pKey = 0; AutomartEntities ae = new AutomartEntities(); var loginData = from p in ae.RegisteredCustomers where p.Email.Equals(userName) select new { p.CustomerPassCode, p.CustomerHashedPassword, p.PersonKey }; int passcode = 0; byte[]hashed = null; int personKey = 0; //if (loginData != null) //{ foreach (var ld in loginData) { passcode = (int)ld.CustomerPassCode; hashed = (byte[])ld.CustomerHashedPassword; personKey = (int)ld.PersonKey; } PasswordHash ph = new PasswordHash(); if (passcode != 0) { byte[] generatedPassword = ph.HashIt(password, passcode.ToString()); if (hashed != null) { if (generatedPassword.SequenceEqual(hashed)) { pKey = personKey; }//end inner if }//end hashed if }//end outer if, passcode return pKey; }
public void WriteCustomer(Customer c) { string sqlPerson = "Insert into Person (PersonLastName, PersonFirstName, PersonUsername, Personpasskey, PersonPlainPassword, " + "PersonUserPassword) Values (@LastName, @FirstName, @Email, @Passcode, @password, @hashedpass)"; PasscodeGenerator pg = new PasscodeGenerator(); PasswordHash ph = new PasswordHash(); int passcode = pg.GetHashCode(); SqlCommand personCmd = new SqlCommand(sqlPerson, connect); personCmd.Parameters.AddWithValue("@LastName", c.LastName); personCmd.Parameters.AddWithValue("@FirstName", c.FirstName); personCmd.Parameters.AddWithValue("@Email", c.Email); personCmd.Parameters.AddWithValue("@Passcode", passcode); personCmd.Parameters.AddWithValue("@Password", c.PlainPassword); personCmd.Parameters.AddWithValue("@hashedPass", ph.HashIt(c.PlainPassword, passcode.ToString())); connect.Open(); personCmd.ExecuteNonQuery(); connect.Close(); }
protected void btnRegister_Click(object sender, EventArgs e) { try { ShowTrackerEntities db = new ShowTrackerEntities(); Fan f = new Fan(); FanLogin fl = new FanLogin(); fl.Fan = f; f.FanName = txtFirstName.Text + " " + txtLastName.Text; f.FanEmail = txtEmail.Text; f.FanDateEntered = DateTime.Now; fl.FanLoginUserName = txtUserName.Text; fl.FanLoginDateAdded = DateTime.Now; fl.FanLoginPasswordPlain = txtPassword.Text; KeyCode kc = new KeyCode(); int code = kc.GetKeyCode(); PasswordHash ph = new PasswordHash(); Byte[] hashed = ph.HashIt(txtPassword.Text, code.ToString()); fl.FanLoginRandom = code; fl.FanLoginHashed = hashed; db.Fans.Add(f); fl.Fan = f; db.FanLogins.Add(fl); db.SaveChanges(); lblErrorSuccess.Text = "Reviewer Saved"; } catch (Exception ex) { lblErrorSuccess.Text = ex.Message; } }
public void WriteCustomer(Customer c) { this.c = c; SqlTransaction tran = null; SqlCommand pCmd = WritePerson(); SqlCommand vCmd = WriteVehicle(); SqlCommand rCmd = WriteRegisteredCustomer(); connect.Open(); try { tran = connect.BeginTransaction(); pCmd.Transaction = tran; vCmd.Transaction = tran; rCmd.Transaction = tran; pCmd.ExecuteNonQuery(); vCmd.ExecuteNonQuery(); rCmd.ExecuteNonQuery(); tran.Commit(); } catch (Exception ex) { tran.Rollback(); throw ex; } finally { connect.Close(); } PasscodeGenerator pg = new PasscodeGenerator(); PasswordHash ph = new PasswordHash(); int passcode = pg.GetPasscode(); }
//Creates and updates some specific keys in the .config file during install. // public ServiceResult InitializeConfigFile(AppInfo appSettings) { AppManager am = new AppManager(Globals.DBConnectionKey, "web", ""); if (string.IsNullOrWhiteSpace(appSettings.AppKey)) { appSettings.AppKey = PasswordHash.CreateHash(Guid.NewGuid().ToString("N")); SaveConfigSetting("AppKey", appSettings.AppKey.Replace(":", "")); } if (string.IsNullOrWhiteSpace(appSettings.AppType)) { appSettings.AppType = "web"; } if (string.IsNullOrWhiteSpace(appSettings.AccountEmail)) { appSettings.AccountEmail = appSettings.UserEmail; } ServiceResult res = am.ValidateInstallSettings(appSettings); if (res.Code != 200) { return(res); } if (string.IsNullOrWhiteSpace(appSettings.ActiveDbConnectionKey)) { appSettings.ActiveDbConnectionKey = appSettings.ActiveDbProvider; } //Create the initial account as the domain if (string.IsNullOrWhiteSpace(appSettings.AccountName)) { appSettings.AccountName = appSettings.SiteDomain; } #region DB connection string connectionString = am.CreateConnectionString(appSettings); if (string.IsNullOrWhiteSpace(connectionString)) { return(ServiceResponse.Error("Failed to create a database connectionstring.")); } string providerName = am.GetDbProviderName(appSettings.ActiveDbProvider); if (string.IsNullOrWhiteSpace(providerName)) { return(ServiceResponse.Error("Failed to create a database providerName.")); } SaveConnectionString(appSettings.ActiveDbProvider, connectionString, providerName); if (string.IsNullOrWhiteSpace(Globals.DBConnectionKey)) { Globals.DBConnectionKey = appSettings.ActiveDbProvider; //set this so after the install it has something to reference. } //Sets the connection key if (!string.IsNullOrWhiteSpace(appSettings.ActiveDbProvider)) { SaveConfigSetting("DefaultDbConnection", appSettings.ActiveDbProvider); } #endregion //This will create permissions for request paths as the come in. Should only be used when adding a new //controller/feature. // if (string.IsNullOrWhiteSpace(AppSetting("AddRequestPermissions"))) { SaveConfigSetting("AddRequestPermissions", "false"); } if (!string.IsNullOrWhiteSpace(appSettings.SiteDomain)) { SaveConfigSetting("SiteDomain", appSettings.SiteDomain); } if (string.IsNullOrWhiteSpace(AppSetting("ApiVersion"))) { SaveConfigSetting("ApiVersion", "1.0");//backlog: have it look in the api folder to get the version } if (string.IsNullOrWhiteSpace(AppSetting("ClientValidationEnabled"))) { SaveConfigSetting("ClientValidationEnabled", "true"); } if (string.IsNullOrWhiteSpace(AppSetting("UseDatabaseConfig"))) { SaveConfigSetting("UseDatabaseConfig", "true"); } if (string.IsNullOrWhiteSpace(AppSetting("ApiStatus"))) { string apiStatus = "PRIVATE"; #if DEBUG apiStatus = "PROTECTED";//using NG server will cut off access because it's on a different port. #endif SaveConfigSetting("ApiStatus", apiStatus); } if (string.IsNullOrWhiteSpace(AppSetting("DBBackupKey"))) { string key = PasswordHash.CreateHash(Guid.NewGuid().ToString("N")); SaveConfigSetting("DBBackupKey", key.Replace(":", "").Substring(0, 11)); } if (!string.IsNullOrWhiteSpace(appSettings.UserName)) { SaveConfigSetting("SiteAdmins", appSettings.UserName?.ToLower()); } if (string.IsNullOrWhiteSpace(AppSetting("SessionLength"))) { SaveConfigSetting("SessionLength", "30"); } if (string.IsNullOrWhiteSpace(AppSetting("TemplateEmailNewMember"))) { SaveConfigSetting("TemplateEmailNewMember", "App_Data\\Templates\\Site\\EmailNewMember.html"); } if (string.IsNullOrWhiteSpace(AppSetting("TemplatePasswordResetEmail"))) { SaveConfigSetting("TemplatePasswordResetEmail", "App_Data\\Templates\\Site\\PasswordResetEmail.html"); } if (string.IsNullOrWhiteSpace(AppSetting("TemplateUserInfoEmail"))) { SaveConfigSetting("TemplateUserInfoEmail", "App_Data\\Templates\\Site\\UserInfoEmail.html"); } if (string.IsNullOrWhiteSpace(AppSetting("EmailStoreTemplateOrderStatusReceived"))) { SaveConfigSetting("EmailStoreTemplateOrderStatusReceived", "App_Data\\Templates\\Store\\EmailOrderReceived.html"); } //Razor versioning. Backlog: depricate when remaining razor tags are removed. if (string.IsNullOrWhiteSpace(AppSetting("webpages:Version"))) { SaveConfigSetting("webpages:Version", "3.0.0.0"); } if (string.IsNullOrWhiteSpace(AppSetting("webpages:Enabled"))) { SaveConfigSetting("webpages:Enabled", "false"); } if (string.IsNullOrWhiteSpace(AppSetting("vs:EnableBrowserLink"))) { SaveConfigSetting("vs:EnableBrowserLink", "false"); } if (string.IsNullOrWhiteSpace(AppSetting("UnobtrusiveJavaScriptEnabled"))) { SaveConfigSetting("UnobtrusiveJavaScriptEnabled", "true"); } return(res); }
public void ScryptGenerateSaltTest() { Assert.AreEqual(32, PasswordHash.ScryptGenerateSalt().Length); }
protected void btnCreate_Click(object sender, EventArgs e) { Page.Validate(); if (userType.SelectedIndex < 1) { reqType.IsValid = false; lblUserStatus.Text = "Choose a type"; } if (Page.IsValid) { //COMMIT VALUES //try { // connect to PBKDF2 database System.Data.SqlClient.SqlConnection sc = new SqlConnection(WebConfigurationManager.ConnectionStrings["connString"].ConnectionString); ViewState["password"] = HttpUtility.HtmlEncode(txtConfirmPw.Value); String strGetUser = "******"; // CHECK FOR EXISTING USERNAMES IN USER RECORD using (SqlCommand getUser = new SqlCommand(strGetUser, sc)) { sc.Open(); getUser.Parameters.AddWithValue("@Username", HttpUtility.HtmlEncode(txtUsername.Text)); SqlDataReader reader = getUser.ExecuteReader(); // if the username exists, process will stop if (reader.HasRows) { txtUsername.Text = null; lblUserStatus.Text = "Username Already Exists!"; } // if the username doesn't exist, it will show failure else { sc.Close(); // INSERT USER RECORD String strCreateUser = "******"; using (SqlCommand createUser = new SqlCommand(strCreateUser, sc)) { sc.Open(); createUser.Parameters.AddWithValue("@FirstName", HttpUtility.HtmlEncode(txtFirstName.Text)); createUser.Parameters.AddWithValue("@LastName", HttpUtility.HtmlEncode(txtLastName.Text)); createUser.Parameters.AddWithValue("@Username", HttpUtility.HtmlEncode(txtUsername.Text)); createUser.Parameters.AddWithValue("@UserType", HttpUtility.HtmlEncode(userType.SelectedValue)); createUser.Parameters.AddWithValue("@LastUpdated", DateTime.Today); createUser.Parameters.AddWithValue("@LastUpdatedBy", HttpUtility.HtmlEncode(Session["Username"].ToString())); createUser.ExecuteNonQuery(); sc.Close(); } // INSERT PASSWORD RECORD AND CONNECT TO USER String strSetPass = "******"; using (SqlCommand setPass = new SqlCommand(strSetPass, sc)) { //try //{ sc.Open(); setPass.Parameters.AddWithValue("@Username", HttpUtility.HtmlEncode(txtUsername.Text)); setPass.Parameters.AddWithValue("@Password", PasswordHash.HashPassword(ViewState["password"].ToString())); // hash entered password setPass.ExecuteNonQuery(); sc.Close(); // Message in the Modal lblStatus.Text = "User Created!"; // Modal popup when submitted ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ModalView", "<script>$(function() { $('#newModal').modal('show'); });</script>", false); //} //catch //{ // lblUserStatus.Text = "Error Submiting Password"; // sc.Close(); //} // Reset Fields txtUsername.Text = null; txtFirstName.Text = null; txtLastName.Text = null; lblUserStatus.Text = " "; } } sc.Close(); } } } }
public ActionResult Index([Bind(Include = "ID,UserName,OldPassword,Password,ConfirmPassword")] Reset reset) { if (ModelState.IsValid) { Contact user = context.ContactSet .Where(a => a.expl_PortalLogin == reset.UserName) .Select(row => row).FirstOrDefault(); string email = user.EMailAddress1; if (null == email) { Session.RemoveAll(); TempData["loginError"] = "Użytkownik nie posiada przypisanego adresu email w systemie CRM."; Session["loggedUser"] = null; return(RedirectToAction("Index", "Login")); } if (null == user) { Session.RemoveAll(); TempData["loginError"] = "Nie ma takiego użytkownika."; Session["loggedUser"] = null; return(RedirectToAction("Index", "Login")); } PasswordHash pHash = PasswordHash.Create(reset.Password); PasswordHash pVerify = null; try { pVerify = PasswordHash.Create(user.expl_salt, user.expl_passwordhash); } catch { Session.RemoveAll(); TempData["loginError"] = "Użytkownik nie może w tej chwili resetować hasła."; Session["loggedUser"] = null; return(RedirectToAction("Index", "Login")); } if (!pVerify.Verify(reset.OldPassword)) { Session.RemoveAll(); TempData["loginError"] = "Wpisz poprawnie stare hasło."; Session["loggedUser"] = null; return(RedirectToAction("Index", "Reset")); } string emailGuid = (context.ContactSet .Where(a => a.expl_PortalLogin == reset.UserName) .Select(row => row.ContactId).FirstOrDefault()).ToString(); Session[emailGuid] = reset.Password; Session[emailGuid + "_hash"] = pHash.Hash; Session[emailGuid + "_salt"] = pHash.Salt; //string link = "<a href='http://localhost:60774/Reset/ResetPassword" + "?id=" + // emailGuid + "'>Resetuj hasło</a>"; string link = "<a href='" + GetBaseUrl() + "Reset/ResetPassword" + "?id=" + emailGuid + "'>Resetuj hasło</a>"; try { var message = new MailMessage(); message.To.Add(new MailAddress(email)); message.From = new MailAddress(ConfigurationManager.AppSettings["email"]); message.Subject = "Reset hasła"; message.Body = "Link do resetu hasła: " + link; message.IsBodyHtml = true; using (var smtp = new SmtpClient()) { var credential = new NetworkCredential { UserName = ConfigurationManager.AppSettings["email_username"], Password = ConfigurationManager.AppSettings["email_password"] }; smtp.Credentials = credential; smtp.Host = ConfigurationManager.AppSettings["email_host"]; smtp.Port = Convert.ToInt16(ConfigurationManager.AppSettings["email_smtp_port"]); smtp.EnableSsl = false; smtp.Send(message); TempData["info"] = "Potwierdzajacy email został wysłany na podany adres email."; return(RedirectToAction("Index", "Login")); } } catch (Exception e) { Session.RemoveAll(); TempData["loginError"] = "Wystąpił błąd. Skontaktuj się z administracją."; return(RedirectToAction("Index", "Login")); } } return(View(reset)); }
public async Task <ActionResult <ApiResultViewModel <AccountViewModel> > > UpdateAccount(string id, [FromBody] AccountInputModel inputModel, CancellationToken cancellationToken) { var account = await _accountManager.GetAsync(id.ToInt(), cancellationToken); if (account is null) { return(NotFound()); } if (account.Email != inputModel.Email && await _accountManager.FindByEmailAsync(inputModel.Email, cancellationToken) != null) { return(BadRequest("duplicate_email", "Account with entered email already exists.")); } account.Email = inputModel.Email; if (!string.IsNullOrWhiteSpace(inputModel.Password)) { account.PasswordHash = PasswordHash.CreateHash(inputModel.Password); } account.PhoneNumber = inputModel.PhoneNumber; account.FirstName = inputModel.FirstName; account.LastName = inputModel.LastName; account.Nickname = inputModel.Nickname; account.GenderId = inputModel.GenderTypeId.ToInt(); account.BirthDate = inputModel.BirthDate; account.StatusId = inputModel.StatusId.ToInt(); account.StatusNote = inputModel.StatusNote; account.IsEmailVerified = inputModel.IsEmailVerified; account.IsPhoneNumberVerified = inputModel.IsPhoneNumberVerified; account.Timezone = "Asia/Tehran"; account.CoverImageId = inputModel.CoverImageId; using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { var selectedAvatarItemIds = inputModel.AvatarItemIds.Select(q => q.ToLong()).ToArray(); if (selectedAvatarItemIds.Any()) { var accountItems = await _accountItemManager.GetByAccountIdAsync(account.Id, cancellationToken); var imagesToCombine = new List <Stream>(); foreach (var selectedAvatarItemId in selectedAvatarItemIds) { var shopItem = await _shopItemManager.GetAsync(selectedAvatarItemId, cancellationToken); imagesToCombine.Add(_fileService.GetFile(shopItem.ImageFileId)); if (!accountItems.Any(q => q.ShopItemId == selectedAvatarItemId)) { // add item to user's items var newAccountItem = new AccountItem { AccountId = account.Id, ShopItemId = selectedAvatarItemId, ItemTypeId = shopItem.TypeId, Quantity = 1 }; newAccountItem = await _accountItemManager.SaveAsync(newAccountItem, cancellationToken); } } using (var avatarImg = _imageProcessingService.Combine(imagesToCombine)) { var fileId = await _fileService.SaveFileAsync(avatarImg, cancellationToken); var file = await _fileManager.SaveAsync(new UploadedFile { FileId = fileId, CreatorAccountId = AccountId, Extension = "png", MimeType = "image/png", MimeTypeCategoryId = UploadedFileMimeTypeCategoryIds.Image, Name = "avatar", Size = avatarImg.Length, TypeId = UploadedFileTypeIds.AccountAvatarImage }, cancellationToken); account.AvatarImageId = file.FileId; } } account.AvatarItemIds = JsonConvert.SerializeObject(selectedAvatarItemIds); account.RoleIds = JsonConvert.SerializeObject(inputModel.RoleIds?.Select(q => q.ToLong()) ?? new long[0]); account = await _accountManager.SaveAsync(account, cancellationToken); await _accountManager.UpdateRolesAsync(account, inputModel.RoleIds.Select(rid => rid.ToLong()), cancellationToken); transaction.Complete(); } return(OkData(AccountViewModel.Map(account))); }
public string CreatePasswordHash(string password) { return(PasswordHash.ScryptHashString(password, PasswordHash.Strength.MediumSlow)); }
//POST: odata/Usuarios/IniciarSesion //Parametros: Email, Password public RespuestaOdata IniciarSesion(ODataActionParameters parameters) { //Inicia sesión y si todo está ok, responde con la patente e ID del vehículo if (parameters == null) { return(new RespuestaOdata() { Id = -1, Patente = "", Mensaje = "error" }); } string emailUser = (string)parameters["Email"]; string pass = (string)parameters["Password"]; bool validado = false; Usuario userEncontrado = db.Usuarios.Where(u => u.Email == emailUser).FirstOrDefault(); if (userEncontrado != null) { validado = PasswordHash.ValidatePassword(pass, userEncontrado.Password); } if (validado == false) { return new RespuestaOdata() { Id = -1, Patente = "", Mensaje = "Email/Contraseña no válidos." } } ; if (userEncontrado.OperadorId == null) { return new RespuestaOdata() { Id = -1, Patente = "", Mensaje = "Usted no tiene auto asignado." } } ; if (userEncontrado.Rol == Usuario.RolUsuario.Bloqueado) { return new RespuestaOdata() { Id = -1, Patente = "", Mensaje = "Cuenta bloqueada" } } ; if (userEncontrado.Operador.Autos.Count == 0) { return new RespuestaOdata() { Id = -1, Patente = "", Mensaje = "Usted no tiene auto asignado" } } ; //int idAuto = userEncontrado.Operador.Auto.Id; //string patenteAuto = userEncontrado.Operador.Auto.Patente; int idAuto = userEncontrado.Operador.Autos.First().Id; string patenteAuto = userEncontrado.Operador.Autos.First().Patente; //Todo ok, responder con la ID y patente que le corresponde return(new RespuestaOdata() { Id = idAuto, Patente = patenteAuto, Mensaje = "Sesión iniciada correctamente." }); }
protected void btnSignUp_Click(object sender, EventArgs e) { string userType = "t"; lbsuccess.Text = ""; System.Data.SqlClient.SqlConnection sc = new System.Data.SqlClient.SqlConnection(); sc.ConnectionString = @"Data Source=aay09edjn65sf6.cpcbbo8ggvx6.us-east-1.rds.amazonaws.com;Initial Catalog=RoomMagnet;Persist Security Info=True;User ID=fahrenheit;Password=cis484fall"; sc.Open(); String firstName = HttpUtility.HtmlEncode(tbFirstName.Text); String lastName = HttpUtility.HtmlEncode(tbLastName.Text); String email = HttpUtility.HtmlEncode(tbTenantEmail.Text); String birthday = HttpUtility.HtmlEncode(tbBirthday.Text); // WILL NEED A METHOD TO CONFIRM EMAIL - DO THAT NEXT String password = HttpUtility.HtmlEncode(tbPassword.Text); String passConfirm = HttpUtility.HtmlEncode(tbPassConfirm.Text); Boolean passwordCorrect = passwordConfirm(password, passConfirm); string address = HttpUtility.HtmlEncode(tbAddress.Text); //splitting up address string[] testArray = new string[2]; int count = 2; string[] seperator = { " " }; string[] strList = address.Split(seperator, count, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < 2; i++) { testArray[i] = strList[i]; } string HouseNumber = testArray[0]; string street = testArray[1]; string DOB = tbBirthday.Text; string city = HttpUtility.HtmlEncode(tbCity.Text); string state = ddState.SelectedValue; string zip = HttpUtility.HtmlEncode(tbZip.Text); DateTime now = DateTime.Now; string phoneNumber = HttpUtility.HtmlEncode(tbPhoneNumber.Text); Tenant tempTenant = new Tenant(firstName, lastName, email, HouseNumber, street, city, state, zip, DOB, userType); // Password security validation Boolean capital = false; Boolean number = false; Boolean special = false; Boolean whiteSpace = true; Boolean minLength = false; Boolean passwordValid = false; if (password.Any(char.IsUpper)) { capital = true; if (password.Any(char.IsDigit)) { number = true; for (int i = 0; i < password.Length; i++) { if (password[i] == '!' || password[i] == '?' || password[i] == '`' || password[i] == '~' || password[i] == '@' || password[i] == '#' || password[i] == '$' || password[i] == '%' || password[i] == '^' || password[i] == '&' || password[i] == '*' || password[i] == '(' || password[i] == ')' || password[i] == '-' || password[i] == '_' || password[i] == '+' || password[i] == '=' || password[i] == ',' || password[i] == '<' || password[i] == '.' || password[i] == '>' || password[i] == '/' || password[i] == '?' || password[i] == '[' || password[i] == '{' || password[i] == ']' || password[i] == '}' || password[i] == ';' || password[i] == ':' || password[i] == '"' || password[i] == '|') { special = true; if (password.Any(char.IsPunctuation)) { special = true; if (password.Length >= 8) { minLength = true; if (password.Any(char.IsWhiteSpace)) { whiteSpace = false; } } } } } } } if (capital == true && number == true && special == true && minLength == true && whiteSpace == true) { passwordValid = true; lblDebug.Text = ""; } else { if (minLength == false) { lblDebug.Text = "Your password must have at least 8 characters"; } if (whiteSpace == false) { lblDebug.Text = "Your password cannot have space"; } if (capital == false || number == false || special == false) { lblDebug.Text = "Your password does not inclueded number, capital letter or special character!"; } } // Email Validation Boolean atSign = false; Boolean comma = false; Boolean emailValid = false; for (int i = 0; i < email.Length; i++) { if (email[i] == '@') { atSign = true; } else if (email[i] == '.') { comma = true; } else { lblDebug.Text = "Please enter correct email format"; } } if (tbTenantEmail.Text == "") { lblDebug.Text = "Please enter your email address"; } if (atSign == true && comma == true) { emailValid = true; lblDebug.Text = ""; } // Name Vaildation Boolean firstNameValid = true; Boolean lastNamevalid = true; Boolean nameValid = true; if (firstName.Any(char.IsNumber)) { firstNameValid = false; lblDebug.Text = "First Name cannot contain a number"; } if (firstName.Any(char.IsWhiteSpace)) { firstNameValid = false; lblDebug.Text = "First Name cannot contain space"; } if (firstName == "") { firstNameValid = false; lblDebug.Text = "Please enter your first name"; } if (lastName.Any(char.IsNumber)) { lastNamevalid = false; lblDebug.Text = "Last Name cannot contain a number"; } if (lastName.Any(char.IsWhiteSpace)) { lastNamevalid = false; lblDebug.Text = "Last Name cannot contain space"; } if (lastName == "") { lastNamevalid = false; lblDebug.Text = "Please enter your last name"; } if (firstNameValid == false || lastNamevalid == false) { nameValid = false; } // phone number vaildation Boolean phoneNumberValid = true; if (phoneNumber.Length < 10) { phoneNumberValid = false; lblDebug.Text = "Plase enter correct phone number"; } if (phoneNumber.Any(char.IsLetter)) { phoneNumberValid = false; lblDebug.Text = "Phone Number cannot contain letters"; } if (phoneNumber.Any(char.IsWhiteSpace)) { phoneNumberValid = false; lblDebug.Text = "Phone Number cannot contain space"; } if (phoneNumber == "") { phoneNumberValid = false; lblDebug.Text = "Please enter your phone number"; } // Birthday Validation Boolean birthdayValid = true; DateTime bod; if (DateTime.TryParse(birthday, out bod) && (!birthday.Contains('-'))) { String.Format("{0:d/MM/yyyy}", bod); var today = DateTime.Today; DateTime bir = DateTime.ParseExact(tbBirthday.Text, "yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture); var age = today.Year - bir.Year; if (bir.Month > today.Month) { age--; } else if (bir.Day > today.Day) { age--; } if (age >= 130 || age < 18) { birthdayValid = false; lblDebug.Text = "You cannot be older than 130 or younger than 18"; } } else { birthdayValid = false; lblDebug.Text = "Please enter correct format of birthday"; } // State Valid Boolean stateValid = true; if (ddState.SelectedValue == "NO") { stateValid = false; lblDebug.Text = "Please choose your state"; } // City validation Boolean cityValid = true; if (city == "") { lblDebug.Text = "Please enter your city name"; cityValid = false; } if (city.Any(char.IsNumber)) { cityValid = false; lblDebug.Text = "City cannot contains a number"; } // ZIP validation Boolean zipValid = true; if (zip.Any(char.IsLetter)) { zipValid = false; lblDebug.Text = "ZIP Code cannot contains a letter"; } if (zip.Length > 5) { zipValid = false; lblDebug.Text = "Please enter correct format of ZIP Code"; } if (zip == "") { zipValid = false; lblDebug.Text = "Please enter ZIP code"; } if (passwordCorrect == true && passwordValid == true && emailValid == true && nameValid == true && phoneNumberValid == true && birthdayValid == true && stateValid == true && cityValid == true && zipValid == true) { //check the email if it is esist System.Data.SqlClient.SqlCommand check_User_Name = new System.Data.SqlClient.SqlCommand(); check_User_Name.Connection = sc; check_User_Name.CommandText = "SELECT * FROM [RMUser] WHERE ([Email] = @Email);"; check_User_Name.Parameters.AddWithValue("@Email", tbTenantEmail.Text); System.Data.SqlClient.SqlDataReader tenantreader = check_User_Name.ExecuteReader(); if (tenantreader.HasRows) { //Username exist lblDebug.Text = "User already exist"; } else { //Username doesn't exist. System.Data.SqlClient.SqlCommand insertTest = new System.Data.SqlClient.SqlCommand(); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@FirstName", firstName)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@LastName", lastName)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Email", email)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@PhoneNumber", phoneNumber)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@DOB", DOB)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@HouseNum", HouseNumber)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Street", street)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@City", city)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@State", state)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Zip", zip)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ModfiedDate", now)); insertTest.Parameters.Add(new System.Data.SqlClient.SqlParameter("@UserType", userType)); insertTest.Connection = sc; tenantreader.Close(); insertTest.CommandText = "Insert into [dbo].[RMUser] VALUES (@FirstName," + "@LastName," + "@Email," + "@PhoneNumber," + "@DOB," + "@HouseNum," + "@Street," + "@City," + "@State," + "@Zip," + "@ModfiedDate," + "@UserType);"; insertTest.ExecuteNonQuery(); System.Data.SqlClient.SqlCommand maxID = new System.Data.SqlClient.SqlCommand(); maxID.Connection = sc; maxID.CommandText = "Select MAX(UserID) from [dbo].[RMUser];"; int tempID = (Int32)maxID.ExecuteScalar(); System.Data.SqlClient.SqlCommand insertPass = new System.Data.SqlClient.SqlCommand(); insertPass.Connection = sc; insertPass.CommandText = "Insert into [dbo].[TenantPassword] values(@MaxID, @Password, @ModifiedDate, @Email);"; insertPass.Parameters.Add(new System.Data.SqlClient.SqlParameter("@MaxID", tempID)); insertPass.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Email", email)); insertPass.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Password", PasswordHash.HashPassword(tbPassword.Text))); insertPass.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ModifiedDate", DateTime.Now)); insertPass.ExecuteNonQuery(); lbsuccess.Text = "Registration success!"; Response.Redirect("MasterTenantDash.aspx"); } } }
protected void NextButton_Click(object sender, EventArgs e) { sc.Open(); System.Data.SqlClient.SqlCommand insert = new System.Data.SqlClient.SqlCommand(); insert.Connection = sc; System.Data.SqlClient.SqlCommand setPass = new System.Data.SqlClient.SqlCommand(); setPass.Connection = sc; System.Data.SqlClient.SqlCommand select = new System.Data.SqlClient.SqlCommand(); select.Connection = sc; try { if (EmailBox.Text.Contains("@") && EmailBox.Text.Length > 0 && ConfirmEmailBox.Text.Length > 0) { EmailErrorLbl.Text = ""; if (EmailBox.Text == ConfirmEmailBox.Text) { EmailErrorLbl.Text = ""; ConfirmEmailErrorLbl.Text = ""; PasswordErrorLbl.Text = ""; ConfirmPasswordErrorLbl.Text = ""; if (PasswordBox.Text.Length >= 8 && ConfirmPasswordBox.Text.Length >= 8) { PasswordErrorLbl.Text = ""; ConfirmPasswordErrorLbl.Text = ""; if (PasswordBox.Text.Contains("!") || PasswordBox.Text.Contains("@") || PasswordBox.Text.Contains("#") || PasswordBox.Text.Contains("$") || PasswordBox.Text.Contains("%") || PasswordBox.Text.Contains("^") || PasswordBox.Text.Contains("&") || PasswordBox.Text.Contains("*") || PasswordBox.Text.Contains("(") || PasswordBox.Text.Contains(")") || PasswordBox.Text.Contains("-") || PasswordBox.Text.Contains("_") || PasswordBox.Text.Contains("+") || PasswordBox.Text.Contains("=")) { PasswordErrorLbl.Text = ""; ConfirmPasswordErrorLbl.Text = ""; if (PasswordBox.Text.Contains("0") || PasswordBox.Text.Contains("1") || PasswordBox.Text.Contains("2") || PasswordBox.Text.Contains("3") || PasswordBox.Text.Contains("4") || PasswordBox.Text.Contains("5") || PasswordBox.Text.Contains("6") || PasswordBox.Text.Contains("7") || PasswordBox.Text.Contains("8") || PasswordBox.Text.Contains("9")) { PasswordErrorLbl.Text = ""; ConfirmPasswordErrorLbl.Text = ""; if (PasswordBox.Text == ConfirmPasswordBox.Text) { PasswordErrorLbl.Text = ""; ConfirmPasswordErrorLbl.Text = ""; setPass.CommandText = "INSERT INTO [dbo].[Passwords] (email, password, userType, lastUpdated, lastUpdatedBy) VALUES " + "(@email, @password, @userType, @lastUpdated, @lastUpdatedBy)"; setPass.Parameters.Add(new SqlParameter("@email", EmailBox.Text)); setPass.Parameters.Add(new SqlParameter("@password", PasswordHash.HashPassword(PasswordBox.Text))); setPass.Parameters.Add(new SqlParameter("@userType", Convert.ToString(Session["userType"]))); setPass.Parameters.Add(new SqlParameter("@lastUpdatedBy", Environment.UserName)); setPass.Parameters.Add(new SqlParameter("@lastUpdated", DateTime.Now)); setPass.ExecuteNonQuery(); Session["userEmail"] = EmailBox.Text; Session["userType"] = Convert.ToString(Session["userType"]); Response.Redirect("CreatePersonalInfo.aspx"); } else { PasswordErrorLbl.Text = "Please make sure both passwords match."; ConfirmPasswordErrorLbl.Text = "Please make sure both passwords match."; } } else { PasswordErrorLbl.Text = "Passsword must contain a number."; if (ConfirmPasswordBox.Text != PasswordBox.Text) { ConfirmPasswordErrorLbl.Text = "Please make sure passwords match."; } } } else { PasswordErrorLbl.Text = "Password must contain a special character."; if (ConfirmPasswordBox.Text != PasswordBox.Text) { ConfirmPasswordErrorLbl.Text = "Please make sure passwords match."; } } } else { PasswordErrorLbl.Text = "Password must be at least 8 characters long."; if (ConfirmPasswordBox.Text != PasswordBox.Text) { ConfirmPasswordErrorLbl.Text = "Please make sure passwords match."; } } } else { EmailErrorLbl.Text = "Please make sure both emails match."; ConfirmEmailErrorLbl.Text = "Please make sure both emails match."; if (PasswordBox.Text == "") { PasswordErrorLbl.Text = "Please enter a valid password."; } if (ConfirmPasswordErrorLbl.Text == "") { ConfirmPasswordErrorLbl.Text = "Please enter a valid password."; } } } else { EmailErrorLbl.Text = "Please enter a valid email address."; if (ConfirmEmailBox.Text == "") { ConfirmEmailErrorLbl.Text = "Please enter a valid email address."; } if (PasswordBox.Text == "") { PasswordErrorLbl.Text = "Please enter a valid password."; } if (ConfirmPasswordBox.Text == "") { ConfirmPasswordErrorLbl.Text = "Please enter a valid password."; } } } catch (Exception ex) { OutputLabel.Text = "An account with this email already exists."; } }
public void ScryptHashStringVerifyTest() { const int OUTPUT = 1; const int PASS = 0; var tests = new List <string[]> { new[] { "^T5H$JYt39n%K*j:W]!1s?vg!:jGi]Ax?..l7[p0v:1jHTpla9;]bUN;?bWyCbtqg nrDFal+Jxl3,2`#^tFSu%v_+7iYse8-cCkNf!tD=KrW)", "$7$B6....1....75gBMAGwfFWZqBdyF3WdTQnWdUsuTiWjG1fF9c1jiSD$tc8RoB3.Em3/zNgMLWo2u00oGIoTyJv4fl3Fl8Tix72" }, new[] { "bl72h6#y<':MFRZ>B IA1=NRkCKS%W8`1I.2uQxJN0g)N N aTt^4K!Iw5r H6;crDsv^a55j9tsk'/GqweZn;cdk6+F_St6:#*=?ZCD_lw>.", "$7$A6....3....Iahc6qM0.UQJHVgE4h9oa1/4OWlWLm9CCtfguvz6bQD$QnXCo3M7nIqtry2WKsUZ5gQ.mY0wAlJu.WUhtE8vF66" }, new[] { "Py >e.5b+tLo@rL`dC2k@eJ&4eVl!W=JJ4+k&mAt@gt',FS1JjqKW3aq21:]^kna`mde7kVkN5NrpKUptu)@4*b&?BE_sJMG1=&@`3GBCV]Wg7xwgo7x3El", "$7$96..../....f6bEusKt79kK4wdYN0ki2nw4bJQ7P3rN6k3BSigsK/D$Dsvuw7vXj5xijmrb/NOhdgoyK/OiSIYv88cEtl9Cik7" }, new[] { "2vj;Um]FKOL27oam(:Uo8+UmSTvb1FD*h?jk_,S=;RDgF-$Fjk?]9yvfxe@fN^!NN(Cuml?+2Raa", "$7$86....I....7XwIxLtCx4VphmFeUa6OGuGJrFaIaYzDiLNu/tyUPhD$U3q5GCEqCWxMwh.YQHDJrlg7FIZgViv9pcXE3h1vg61" }, new[] { "CT=[9uUoGav,J`kU+348tA50ue#sL:ABZ3QgF+r[#vh:tTOiL>s8tv%,Jeo]jH/_4^i(*jD-_ku[9Ko[=86 06V", "$7$A6....2....R3.bjH6YS9wz9z8Jsj.3weGQ3J80ZZElGw2oVux1TP6$i5u6lFzXDHaIgYEICinLD6WNaovbiXP8SnLrDRdKgA9" }, new[] { "J#wNn`hDgOpTHNI.w^1a70%f,.9V_m038H_JIJQln`vdWnn/rmILR?9H5g(+`;@H(2VosN9Fgk[WEjaBr'yB9Q19-imNa04[Mk5kvGcSn-TV", "$7$B6....1....Dj1y.4mF1J9XmT/6IDskYdCLaPFJTq9xcCwXQ1DpT92$92/hYfZLRq1nTLyIz.uc/dC6wLqwnsoqpkadrCXusm6" }, new[] { "j4BS38Asa;p)[K+9TY!3YDj<LK-`nLVXQw9%*QfM", "$7$B6....1....5Ods8mojVwXJq4AywF/uI9BdMSiJ/zT8hQP/4cB68VC$nk4ExHNXJ802froj51/1wJTrSZvTIyyK7PecOxRRaz0" }, new[] { "M.R>Qw+!qJb]>pP :_.9`dxM9k [eR7Y!yL-3)sNs[R,j_/^ TH=5ny'15>6UXWcQW^6D%XCsO[vN[%ReA-`tV1vW(Nt*0KVK#]45P_A", "$7$B6....1....D/eyk8N5y6Z8YVQEsw521cTx.9zzLuK7YDs1KMMh.o4$alfW8ZbsUWnXc.vqon2zoljVk24Tt1.IsCuo2KurvS2" }, new[] { "K3S=KyH#)36_?]LxeR8QNKw6X=gFb'ai$C%29V* tyh^Wo$TN-#Q4qkmtTCf0LLb.^E$0uykkP", "$7$B6....1....CuBuU97xgAage8whp/JNKobo0TFbsORGVbfcQIefyP8$aqalP.XofGViB8EPLONqHma8vs1xc9uTIMYh9CgE.S8" }, new[] { "Y0!?iQa9M%5ekffW(`", "$7$A6....1....TrXs5Zk6s8sWHpQgWDIXTR8kUU3s6Jc3s.DtdS8M2i4$a4ik5hGDN7foMuHOW.cp.CtX01UyCeO0.JAG.AHPpx5" } }; foreach (var test in tests) { Assert.IsTrue(PasswordHash.ScryptHashStringVerify(test[OUTPUT], test[PASS])); } }
private Account(Username username, PasswordHash passwordHash, Name name, Roles role) : this(new AccountId(Guid.NewGuid()), username, passwordHash, name, role) { }
public void HashSalsa208Sha256LongTest() { //Some of the values are from: https://github.com/jedisct1/libsodium/blob/master/test/default/pwhash_scrypt.c var testObjects = new List <HashTestObject> { new HashTestObject { Password = "******", Salt = "5541fbc995d5c197ba290346d2c559dedf405cf97e5f95482143202f9e74f5c2", OpsLimit = 481326, MemLimit = 7256678, OutputLength = 155 }, new HashTestObject { Password = "******", Salt = "f1192dd5dc2368b9cd421338b22433455ee0a3699f9379a08b9650ea2c126f0d", OpsLimit = 695191, MemLimit = 15738350, OutputLength = 55 }, new HashTestObject { Password = "******", Salt = "3b840e20e9555e9fb031c4ba1f1747ce25cc1d0ff664be676b9b4a90641ff194", OpsLimit = 535778, MemLimit = 7849083, OutputLength = 250 }, new HashTestObject { Password = "******", Salt = "eb2a3056a09ad2d7d7f975bcd707598f24cd32518cde3069f2e403b34bfee8a5", OpsLimit = 311757, MemLimit = 7994791, OutputLength = 249 }, new HashTestObject { Password = "******", Salt = "3ee91a805aa62cfbe8dce29a2d9a44373a5006f4a4ce24022aca9cecb29d1473", OpsLimit = 758010, MemLimit = 5432947, OutputLength = 190 }, new HashTestObject { Password = "******", Salt = "039c056d933b475032777edbaffac50f143f64c123329ed9cf59e3b65d3f43b6", OpsLimit = 233177, MemLimit = 13101817, OutputLength = 212 }, new HashTestObject { Password = "******", Salt = "90631f686a8c3dbc0703ffa353bc1fdf35774568ac62406f98a13ed8f47595fd", OpsLimit = 234753, MemLimit = 4886999, OutputLength = 178 }, new HashTestObject { Password = "******", Salt = "44071f6d181561670bda728d43fb79b443bb805afdebaf98622b5165e01b15fb", OpsLimit = 78652, MemLimit = 6631659, OutputLength = 231 }, new HashTestObject { Password = "******", Salt = "3d968b2752b8838431165059319f3ff8910b7b8ecb54ea01d3f54769e9d98daf", OpsLimit = 717248, MemLimit = 10784179, OutputLength = 167 } }; foreach (var testObject in testObjects) { Assert.AreEqual(testObject.OutputLength, PasswordHash.ScryptHashBinary(Utilities.HexToBinary(testObject.Password), Utilities.HexToBinary(testObject.Salt), testObject.OpsLimit, testObject.MemLimit, testObject.OutputLength) .Length); } }
public void ArgonGenerateSaltTest() { Assert.AreEqual(16, PasswordHash.ArgonGenerateSalt().Length); }
public void TestGenerateSalt() { Assert.AreEqual(32, PasswordHash.GenerateSalt().Length); }
public async Task <IdResponse> Register([FromBody] User newUser) { var ps = new IdResponse(); try { newUser.Email = newUser.Email?.ToLower(); //check if there are already users with this email if (!db.Users.Any(u => u.Email == newUser.Email)) //check for valid email { if (!string.IsNullOrWhiteSpace(newUser.Email) && !string.IsNullOrWhiteSpace(newUser.Password) && new EmailAddressAttribute().IsValid(newUser.Email)) { if (await PasswordCheck.IsStrong(newUser.Password)) { //if all good, convert the password into its hash newUser.Password = PasswordHash.HashPassword(newUser.Password); //save the user // ReSharper disable once MethodHasAsyncOverload db.Users.Add(newUser); await db.SaveChangesAsync(); //let the client know that it was done successfully by returning the Id ps.Id = newUser.Id; //save the user's ID to the session -- ie. we're logged in await HttpContext.Session.LoadAsync(); HttpContext.Session.SetInt32("UserId", newUser.Id); await HttpContext.Session.CommitAsync(); logger.LogTrace($"Created user {newUser.Id} for {newUser.Email}"); } else { logger.LogWarning($"attempt to use poor password {newUser.Password}"); ps.ResponseCodes.Add(ResponseCodes.WeakPassword); } } else { logger.LogWarning($"missing info: {newUser}"); ps.ResponseCodes.Add(ResponseCodes.InvalidCredentials); } } else { logger.LogWarning($"email {newUser.Email} already exists"); ps.ResponseCodes.Add(ResponseCodes.EmailInUse); } } catch (Exception ex) { logger.LogError(ex, $"failed to create user {newUser}"); ps.ResponseCodes.Add(ResponseCodes.InternalError); } return(ps); }
//Use method in order to validate user information. protected void btnSignUpHomeOwner_Click(object sender, EventArgs e) { int age = getAge(birthDate.Value); bool validate; //check if the Host is already existing sc.Open(); System.Data.SqlClient.SqlCommand readHost = new System.Data.SqlClient.SqlCommand(); readHost.Connection = sc; readHost.CommandText = "SELECT HostEmail FROM Homeowner WHERE HostEmail = upper(@HostEmail);"; readHost.Parameters.Add(new SqlParameter("@HostEmail", txtEmail.Value)); System.Data.SqlClient.SqlDataReader reader = readHost.ExecuteReader(); if (reader.HasRows) { lblHomeEmailNo.ForeColor = Color.Red; lblHomeEmailNo.Text = "*A Host account already exists for this email."; lblHomeEmailNo.Visible = true; validate = false; } else { validate = true; } sc.Close(); //--------------------------- if (validate == true) { //cheak if tenant age greater than 18 if (age >= 18) { validate = true; sc.Open(); String email = HttpUtility.HtmlEncode(txtEmail.Value); String phone = HttpUtility.HtmlEncode(txtHomePhone.Value); String firstName = HttpUtility.HtmlEncode(txtFName.Value); String lastName = HttpUtility.HtmlEncode(txtLName.Value); DateTime dob = Convert.ToDateTime(HttpUtility.HtmlEncode(birthDate.Value)); String password = HttpUtility.HtmlEncode(txtPassword.Value); DateTime lastUpdated = DateTime.Today; String zip = HttpUtility.HtmlEncode(txtZip.Value); String state = inputState.Value; String address = HttpUtility.HtmlEncode(inputAddress.Value); String cityCo = HttpUtility.HtmlEncode(inputCity.Value); Homeowner newHomeowner = new Homeowner(firstName, lastName, email, phone, address, cityCo, state, password, dob, zip, lastUpdated); FileUpload img = (FileUpload)imgUpload; Byte[] imgByte = null; if (img.HasFile && img.PostedFile != null) { //To create a PostedFile HttpPostedFile File = imgUpload.PostedFile; //Create byte Array with file len imgByte = new Byte[File.ContentLength]; //force the control to load data in array File.InputStream.Read(imgByte, 0, File.ContentLength); // Create new Insert Command System.Data.SqlClient.SqlCommand insertHomeOwner = new System.Data.SqlClient.SqlCommand(); insertHomeOwner.Connection = sc; insertHomeOwner.CommandText = "INSERT INTO HOMEOWNER VALUES(@First, @Last, @Email, @Phone, @Pass, @Street, @CityCo,@State, @Zip, @Dob, @LU, @hImage, null, 'Y')"; insertHomeOwner.Parameters.Add(new SqlParameter("@First", newHomeowner.getHostFirstName())); insertHomeOwner.Parameters.Add(new SqlParameter("@Last", newHomeowner.getHostLastName())); insertHomeOwner.Parameters.Add(new SqlParameter("@Email", newHomeowner.getHostEmail())); insertHomeOwner.Parameters.Add(new SqlParameter("@Phone", newHomeowner.getHostphoneNum())); insertHomeOwner.Parameters.Add(new SqlParameter("@Pass", PasswordHash.HashPassword(password))); // Password hash insertHomeOwner.Parameters.Add(new SqlParameter("@Street", newHomeowner.getAddress())); insertHomeOwner.Parameters.Add(new SqlParameter("@CityCo", newHomeowner.getHostcityCo())); insertHomeOwner.Parameters.Add(new SqlParameter("@State", newHomeowner.getHoststate())); insertHomeOwner.Parameters.Add(new SqlParameter("@Zip", newHomeowner.getZip())); insertHomeOwner.Parameters.Add(new SqlParameter("@Dob", newHomeowner.getHomeDOB())); insertHomeOwner.Parameters.Add(new SqlParameter("@LU", lastUpdated)); insertHomeOwner.Parameters.Add(new SqlParameter("@hImage", imgByte)); insertHomeOwner.ExecuteNonQuery(); sc.Close(); ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true); txtEmail.Value = ""; txtPassword.Value = ""; txtFName.Value = ""; txtLName.Value = ""; inputAddress.Value = ""; inputCity.Value = ""; txtZip.Value = ""; txtHomePhone.Value = ""; birthDate.Value = ""; inputState.SelectedIndex = -1; lblHomeBDNo.Text = ""; lblHomeEmailFormat.Text = ""; lblHomeEmailNo.Text = ""; lblHomeBDNo.Visible = false; lblHomeEmailFormat.Visible = false; lblHomeEmailNo.Visible = false; lblUpPic.Visible = false; } else { lblUpPic.ForeColor = Color.Red; lblUpPic.Text = "*Homeowner must upload a profile photo"; lblUpPic.Visible = true; validate = false; } } else { lblHomeBDNo.ForeColor = Color.Red; lblHomeBDNo.Text = "*Homeowner must be 18 years old or above"; lblHomeBDNo.Visible = true; validate = false; } } }
public ActionResult edit(FormCollection collection) { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get the return url string returnUrl = collection["returnUrl"]; ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Get all the form values Int32 id = Convert.ToInt32(collection["txtId"]); string user_name = collection["txtUserName"]; string password = collection["txtPassword"]; string role = collection["selectAdminRole"]; string email = collection["txtEmail"]; string author_name = collection["txtAuthorName"]; string author_description = collection["txtAuthorDescription"]; string facebook_user_id = collection["txtFacebookUserId"]; string google_user_id = collection["txtGoogleUserId"]; // Get the default admin language id Int32 adminLanguageId = currentDomain.back_end_language; // Get translated texts KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC"); // Get the administrator Administrator administrator = Administrator.GetOneById(id, adminLanguageId); bool postExists = true; // Check if the administrator exists if (administrator == null) { // Create an empty administrator administrator = new Administrator(); postExists = false; } // Update values administrator.admin_user_name = user_name; administrator.admin_role = role; administrator.email = email; administrator.author_name = author_name; administrator.author_description = author_description; administrator.facebook_user_id = facebook_user_id; administrator.google_user_id = google_user_id; // Create a error message string errorMessage = string.Empty; // Get a administrator on user name Administrator adminOnUserName = Administrator.GetOneByUserName(user_name); // Check for errors in the administrator if (adminOnUserName != null && administrator.id != adminOnUserName.id) { errorMessage += "• " + String.Format(tt.Get("error_field_unique"), tt.Get("user_name")) + "<br/>"; } if (administrator.admin_user_name.Length > 50) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("user_name"), "50") + "<br/>"; } if (administrator.author_name.Length > 50) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("name"), "50") + "<br/>"; } if (AnnytabDataValidation.IsEmailAddressValid(administrator.email) == null) { errorMessage += "• " + tt.Get("error_email_valid") + "<br/>"; } if (administrator.facebook_user_id.Length > 50) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), "Facebook user id", "50") + "<br/>"; } if (administrator.google_user_id.Length > 50) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), "Google user id", "50") + "<br/>"; } // Check if there is errors if (errorMessage == string.Empty) { // Check if we should add or update the administrator if (postExists == false) { // Add the administrator Int32 insertId = (Int32)Administrator.AddMasterPost(administrator); administrator.id = insertId; Administrator.AddLanguagePost(administrator, adminLanguageId); Administrator.UpdatePassword(insertId, PasswordHash.CreateHash(password)); } else { // Update the administrator Administrator.UpdateMasterPost(administrator); Administrator.UpdateLanguagePost(administrator, adminLanguageId); // Only update the password if it has changed if (password != "") { Administrator.UpdatePassword(administrator.id, PasswordHash.CreateHash(password)); } } // Redirect the user to the list return Redirect(returnUrl); } else { // Set form values ViewBag.ErrorMessage = errorMessage; ViewBag.Administrator = administrator; ViewBag.TranslatedTexts = tt; ViewBag.ReturnUrl = returnUrl; // Return the edit view return View("edit"); } } // End of the edit method
protected void MasterPageSignUp_Click(object sender, EventArgs e) { //EmailSender email = new EmailSender(); //email.SendWelcomeMail(MasterPageEmail.Text); //Not working in showker Lab if (SignUpEmailCustomValidator.IsValid && CustomValidator1.IsValid) { Users users = new Users(MasterPageFirstName.Text, MasterPageLastName.Text, MasterPageEmail.Text, MasterPagePassword.Text, MasterPageAgeRangeDropDownList.SelectedValue); string Welcomemailstring = "Welcome to RoomMagnet!"; string EnteredEmailAddress = MasterPageEmail.Text; EmailSender email = new EmailSender(); email.SendWelcomeMail(EnteredEmailAddress, Welcomemailstring); string MasterPagepassword = users.getPassword(); string HashedPassword = PasswordHash.HashPassword(MasterPagepassword); try { if (cn.State == System.Data.ConnectionState.Closed) { cn.Open(); } string Sql = "insert into Users (FirstName,LastName,Email,Password,AgeRange,UserRole,Verified,SignUpDate,LastUpdated,LastUpdatedBy,[ImagePath]) values(@FirstName,@LastName,@Email,@Password,@AgeRange,@UserRole,@Verified,@SignUpDate,@LastUpdated,@LastUpdatedBy,@ImagePath)"; SqlCommand sqlCommand = new SqlCommand(Sql, cn); string role = "Renter"; string verified = "Unverified"; byte[] imgdata = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/img/40x40.png")); sqlCommand.Parameters.AddRange( new SqlParameter[] { new SqlParameter("@FirstName", users.getFirstName()), new SqlParameter("@LastName", users.getLastName()), new SqlParameter("@Email", users.getEmail()), new SqlParameter("@Password", HashedPassword), new SqlParameter("@AgeRange", users.getAgeRange()), new SqlParameter("@LastUpdated", users.getLastUpdated()), new SqlParameter("@LastUpdatedBy", users.getLastUpdatedBy()), new SqlParameter("@SignUpDate", DateTime.Now), new SqlParameter("@UserRole", role), new SqlParameter("@ImagePath", imgdata), new SqlParameter("@Verified", verified), }); sqlCommand.ExecuteNonQuery(); cn.Close(); ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openNotificationModal();", true); MasterPageAgeRangeDropDownList.SelectedIndex = 0; MasterPageComfirmPassword.Text = string.Empty; MasterPageEmail.Text = string.Empty; MasterPageFirstName.Text = string.Empty; MasterPageLastName.Text = string.Empty; MasterPagePassword.Text = string.Empty; } // client -side to show a notification catch (Exception) { // client -side to show a error notification } } else { // lBL } }
private bool CheckPassword(string passwordHashAndSalt, string password) { return(PasswordHash.ScryptHashStringVerify(passwordHashAndSalt, password)); }
public void ToStringTest(string passwordHash) { Assert.Equal(passwordHash, PasswordHash.Parse(passwordHash).ToString()); }
public Response ResetPassword(string phonenumber, string password) { try { if (new UserRepository.UserRepository(language).UpdatePasswordByPhone(phonenumber, PasswordHash.CreateHash(password))) { // And Get The profile Data By PhoneNumber return(new Response(true, Messages.GetMessage(language, Messages.TypeM.SERVICE, Messages.serviceM.SERVICE_CHANGE_PASSWORD))); } else { return(new Response(true, Messages.GetMessage(language, Messages.TypeM.SERVICE, Messages.serviceM.SERVICE_CHANGE_PASSWORD))); } } catch (UpdateException UpdateException) { return(new Response(false, UpdateException.RespMessage, UpdateException.ErrorMessage)); } catch (Exception ex) { return(new Response(false, Messages.GetMessage(language, Messages.TypeM.DEFAULT, Messages.defaultM.UNEXPERROR), ex.Message)); } }
protected void NextButton_Click(object sender, EventArgs e) { try { sc.Open(); System.Data.SqlClient.SqlCommand findPass = new System.Data.SqlClient.SqlCommand(); findPass.Connection = sc; System.Data.SqlClient.SqlCommand select = new System.Data.SqlClient.SqlCommand(); select.Connection = sc; // SELECT PASSWORD STRING WHERE THE ENTERED USERNAME MATCHES select.CommandText = "select userType from Passwords where email = @email0"; select.Parameters.Add(new System.Data.SqlClient.SqlParameter("@email0", HttpUtility.HtmlEncode(EmailBox.Text))); String userType = Convert.ToString(select.ExecuteScalar()); if (userType == "T") { select.CommandText = "Select active from tenant where email = @email11"; select.Parameters.Add(new System.Data.SqlClient.SqlParameter("@email11", HttpUtility.HtmlEncode(EmailBox.Text))); tenantActive = Convert.ToString(select.ExecuteScalar()); } else if (userType == "H") { select.CommandText = "Select active from host where email = @email12"; select.Parameters.Add(new System.Data.SqlClient.SqlParameter("@email12", HttpUtility.HtmlEncode(EmailBox.Text))); hostActive = Convert.ToString(select.ExecuteScalar()); } findPass.CommandText = "select password from Passwords where email = @email"; findPass.Parameters.Add(new System.Data.SqlClient.SqlParameter("@email", HttpUtility.HtmlEncode(EmailBox.Text))); SqlDataReader reader = findPass.ExecuteReader(); if (reader.HasRows) // if the username exists, it will continue { while (reader.Read()) // this will read the single record that matches the entered username { string storedHash = reader["password"].ToString(); // store the database password into this variable if (PasswordHash.ValidatePassword(PasswordBox.Text, storedHash)) // if the entered password matches what is stored, it will show success { OutputLabel.Text = "Success!"; NextButton.Enabled = false; EmailBox.Enabled = false; PasswordBox.Enabled = false; //Then, open the database and sc.Close(); sc.Open(); //select.CommandText = "select userType from Passwords where email = @email"; //select.Parameters.Add(new System.Data.SqlClient.SqlParameter("@email", EmailBox.Text)); //String userType = Convert.ToString(select.ExecuteScalar()); select.CommandText = "select userType from Passwords where email = @email2"; select.Parameters.Add(new System.Data.SqlClient.SqlParameter("@email2", EmailBox.Text)); Session["userType"] = HttpUtility.HtmlEncode(Convert.ToString(select.ExecuteScalar())); select.CommandText = "Select email from Passwords where email = @email3"; select.Parameters.Add(new System.Data.SqlClient.SqlParameter("@email3", EmailBox.Text)); Session["userEmail"] = HttpUtility.HtmlEncode(Convert.ToString(select.ExecuteScalar())); //Create a cookie so we can check if browser session is still alive baby. HttpCookie httpCookie = new HttpCookie("Session"); httpCookie["loggedin"] = "true"; Response.Cookies.Add(httpCookie); if (Convert.ToString(Session["userType"]) == "T") { if (tenantActive == "F") { OutputLabel.Text = "Your account has been deactivated. Please contact an administrator for more information."; Session["userType"] = ""; Session["userEmail"] = ""; break; } else { Response.Redirect("TenantDashboard.aspx"); } } else if (Convert.ToString(Session["userType"]) == "H") { if (hostActive == "F") { OutputLabel.Text = "Your account has been deactivated. Please contact an administrator for more information."; Session["userType"] = ""; Session["userEmail"] = ""; break; } else { Response.Redirect("HostDashboard.aspx"); } } else if (Convert.ToString(Session["userType"]) == "A") { Response.Redirect("AdminDashboard.aspx"); } else { //nothing } sc.Close(); } else { OutputLabel.Text = "Password is wrong."; } } } else // if the username doesn't exist, it will show failure { OutputLabel.Text = "Login failed."; } } catch (Exception ex) { OutputLabel.Text = "Database Error." + ex; } }
protected void LoginButton_Click(object sender, EventArgs e) { try { sc.Open(); System.Data.SqlClient.SqlCommand findPass = new System.Data.SqlClient.SqlCommand(); findPass.Connection = sc; System.Data.SqlClient.SqlCommand select = new System.Data.SqlClient.SqlCommand(); select.Connection = sc; // SELECT PASSWORD STRING WHERE THE ENTERED USERNAME MATCHES findPass.CommandText = "select password from Passwords where email = @email"; findPass.Parameters.Add(new System.Data.SqlClient.SqlParameter("@email", HttpUtility.HtmlEncode(EmailBox.Text))); SqlDataReader reader = findPass.ExecuteReader(); if (reader.HasRows) // if the username exists, it will continue { while (reader.Read()) // this will read the single record that matches the entered username { string storedHash = reader["password"].ToString(); // store the database password into this variable if (PasswordHash.ValidatePassword(PasswordBox.Text, storedHash)) // if the entered password matches what is stored, it will show success { OutputLabel.Text = "Success!"; LoginButton.Enabled = false; EmailBox.Enabled = false; PasswordBox.Enabled = false; //Then, open the database and sc.Close(); sc.Open(); //select.CommandText = "select userType from Passwords where email = @email"; //select.Parameters.Add(new System.Data.SqlClient.SqlParameter("@email", EmailBox.Text)); //String userType = Convert.ToString(select.ExecuteScalar()); select.CommandText = "select userType from Passwords where email = @email2"; select.Parameters.Add(new System.Data.SqlClient.SqlParameter("@email2", EmailBox.Text)); Session["userType"] = Convert.ToString(select.ExecuteScalar()); select.CommandText = "Select email from Passwords where email = @email3"; select.Parameters.Add(new System.Data.SqlClient.SqlParameter("@email3", EmailBox.Text)); Session["userEmail"] = Convert.ToString(select.ExecuteScalar()); Response.Redirect("Dashboard.aspx"); sc.Close(); } else { OutputLabel.Text = "Password is wrong."; } } } else // if the username doesn't exist, it will show failure { OutputLabel.Text = "Login failed."; } } catch (Exception ex) { OutputLabel.Text = "Database Error." + ex; } }
/// <summary>Method which converts a raw, plan-text password into a hashed password using Argon2.</summary> private void Hash() { HashedPassword = PasswordHash.ArgonHashString(RawPassword, Strength); }
/// <summary> /// Validates the user's token in tbl_forgotten_password /// </summary> private ResetPasswordInputModel validateToken(ResetPasswordInputModel inputModel) { string customerNumber = string.Empty; string token = string.Empty; string hashedToken = string.Empty; PasswordHash passHash = new PasswordHash(); DataTable tokenRows = new DataTable(); DateTime timeNow; customerNumber = inputModel.CustomerNumber; token = inputModel.Token; timeNow = inputModel.DateNow; hashedToken = passHash.HashTokenWithCurrentAlgorithm(token); //Get row from table tokenRows = TDataObjects.ProfileSettings.tblForgottenPassword.GetByHashedToken(hashedToken); if (tokenRows.Rows.Count > 0) { //Check everything individually. Since certain patterns indicate hacking attempts and should be logged if (tokenRows.Rows.Count > 1) { TDataObjects.ProfileSettings.tblForgottenPassword.SetTokenAsUsed(hashedToken); _talCust.Settings.Logging.ErrorObjectLog("ResetPassword.aspx - Reset Password validation fail", "RPW-001", "More than 1 token found in tbl_forgotten_password. Customer number:" + inputModel.CustomerNumber, "PasswordEncryptionLog"); } else { //Check customer number if (tokenRows.Rows[0]["CUSTOMER_NUMBER"].ToString().Trim() == customerNumber) { inputModel.IsCustomerValid = true; inputModel.EmailAddress = tokenRows.Rows[0]["EMAIL_ADDRESS"].ToString().Trim(); inputModel.UserName = customerNumber; } else { inputModel.IsCustomerValid = false; _talCust.Settings.Logging.ErrorObjectLog("ResetPassword.aspx - Reset Password validation fail", "RPW-002", "customer number in tbl_forgotten_password doesn't match the requested token. A user is attempting to reset a password suspiciously with the customer number:" + inputModel.CustomerNumber, "PasswordEncryptionLog"); } //Check token if (tokenRows.Rows[0]["HASHED_TOKEN"].ToString().Trim() == hashedToken) { inputModel.IsTokenValid = true; inputModel.HashedToken = hashedToken; } else { inputModel.IsTokenValid = false; _talCust.Settings.Logging.ErrorObjectLog("ResetPassword.aspx - Reset Password validation fail", "RPW-003", "hashed token in tbl_forgotten_password doesn't match the requested token. A user is attempting to reset a password suspiciously with the customer number:" + inputModel.CustomerNumber, "PasswordEncryptionLog"); } //Check date if (Convert.ToDateTime(tokenRows.Rows[0]["EXPIRE_TIMESTAMP"]) >= timeNow) { inputModel.IsDateValid = true; } else { inputModel.IsDateValid = false; _talCust.Settings.Logging.ErrorObjectLog("ResetPassword.aspx - Reset Password validation fail", "RPW-004", "The date in tbl_forgotten_password doesn't match the requested token. Token has probably expired customer number:" + inputModel.CustomerNumber, "PasswordEncryptionLog"); } //If everything is valid then the input model is valid if (inputModel.IsTokenValid && inputModel.IsDateValid && inputModel.IsCustomerValid) { inputModel.IsValid = true; } else { inputModel.IsValid = false; } } } else { //Token not valid, error. inputModel.IsValid = false; _talCust.Settings.Logging.ErrorObjectLog("ResetPassword.aspx - Reset Password validation fail", "RPW-000", "No token found in tbl_forgotten_password. A user is attempting to reset a password suspiciously with the customer number:" + inputModel.CustomerNumber, "PasswordEncryptionLog"); } return(inputModel); }
public User(CreateUserRequest req) { Email = req.Email; Username = req.Username; Password = PasswordHash.Hash(req.Password); }
private void GetNewHash() { //get the new hash PasswordHash h = new PasswordHash(); newHash = h.HashIt(pass, seed.ToString()); }
public static string Hash(string password) { return(PasswordHash.CreateHash(password)); }
public void HashArgonLongTest() { try { //Could cause OutOfMemoryException //Some of the values are from: https://github.com/jedisct1/libsodium/blob/master/test/default/pwhash_scrypt.c var testObjects = new List <HashTestObject> { new HashTestObject { Password = "******", Salt = "5541fbc995d5c197ba290346d2c559de", OpsLimit = 5, MemLimit = 7256678, OutputLength = 155 }, new HashTestObject { Password = "******", Salt = "f1192dd5dc2368b9cd421338b2243345", OpsLimit = 4, MemLimit = 7849083, OutputLength = 250 }, new HashTestObject { Password = "******", Salt = "3b840e20e9555e9fb031c4ba1f1747ce", OpsLimit = 3, MemLimit = 7994791, OutputLength = 249 }, new HashTestObject { Password = "******", Salt = "eb2a3056a09ad2d7d7f975bcd707598f", OpsLimit = 4, MemLimit = 1397645, OutputLength = 152 }, new HashTestObject { Password = "******", Salt = "39d82eef32010b8b79cc5ba88ed539fb", OpsLimit = 3, MemLimit = 1432947, OutputLength = 82 }, new HashTestObject { Password = "******", Salt = "039c056d933b475032777edbaffac50f", OpsLimit = 3, MemLimit = 4886999, OutputLength = 156 }, new HashTestObject { Password = "******", Salt = "3d968b2752b8838431165059319f3ff8", OpsLimit = 3, MemLimit = 1784128, OutputLength = 220 } }; foreach (var testObject in testObjects) { Assert.AreEqual(testObject.OutputLength, PasswordHash.ArgonHashBinary(Utilities.HexToBinary(testObject.Password), Utilities.HexToBinary(testObject.Salt), testObject.OpsLimit, testObject.MemLimit, testObject.OutputLength) .Length); } } catch (OutOfMemoryException e) { Assert.Inconclusive(e.ToString()); } }
public string Get(string id) { return(PasswordHash.HashPassword(id)); }