public Boolean AddUser(User user) { var email = user.Email; user.Passw = HashSalt.Hash_Salt(user.Passw); using (IDbConnection dbConnection = Connection) { string sQuery0 = "SELECT FirstName FROM Customer WHERE Email = @email"; dbConnection.Open(); string result = dbConnection.QueryFirstOrDefault <String>(sQuery0, new { @Email = email }); dbConnection.Close(); if (String.IsNullOrEmpty(result)) { string sQuery = "INSERT INTO Customer(FirstName,LastName,Passw,Email)" + "VALUES(@firstName,@lastName,@passw,@email)"; dbConnection.Open(); dbConnection.Execute(sQuery, user); return(true); } else { return(false); } } }
public void Execute(ApplicationUser request) { var item = context.ApplicaitonUsers.Find(_actor.Id); if (request.FirstName != null) { item.FirstName = request.FirstName; } if (request.LastName != null) { item.LastName = request.LastName; } if (request.Email != null) { item.Email = request.Email; } if (request.Password != null) { HashSalt hashSalt = Password.GenerateSaltedHash(64, request.Password); item.Password = hashSalt.Hash; item.Salt = hashSalt.Salt; } item.UpdatedAt = DateTime.Now; context.SaveChanges(); }
public void Register(string nric, string password, string associatedTokenID, string firstName, string lastName, string countryOfBirth, string nationality, string sex, string gender, string MaritalStatus, string address, string addressPostalCode, string email, string contactNumber, DateTime dateOfBirth, List <string> roles) { if (!IsAdministrator()) { return; } HashSalt hashSalt = GenerateSaltedHash(password); Account account = new Account { nric = nric, salt = hashSalt.Salt, hash = hashSalt.Hash, associatedTokenID = associatedTokenID, firstName = firstName, lastName = lastName, countryOfBirth = countryOfBirth, nationality = nationality, sex = sex, gender = gender, maritalStatus = MaritalStatus, address = address, addressPostalCode = addressPostalCode, email = email, contactNumber = contactNumber, dateOfBirth = dateOfBirth }; if (string.IsNullOrEmpty(associatedTokenID)) { account.status = 2; } else { account.status = 1; } accountDAL.Insert(account); logBLL.LogEvent(GetNRIC(), "Register Account", "Subject NRIC: " + nric + "."); if (roles.Contains("Patient")) { RoleEnablePatient(account.nric); } if (roles.Contains("Therapist")) { RoleEnableTherapist(account.nric); } if (roles.Contains("Researcher")) { RoleEnableResearcher(account.nric); } if (roles.Contains("Administrator")) { RoleEnableAdmin(account.nric); } }
public HashSalt GetHashValue(string input) { CustomSaltFunction saltFunc = new CustomSaltFunction(); string salt = saltFunc.GetSaltValue(32); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(input + salt); SHA256 sha = new SHA256Cng(); // Hash function byte[] hash = sha.ComputeHash(bytes); // Generate hash in bytes // Store the hash value as string with uppercase letters. StringBuilder hashPassword = new StringBuilder(); // To store the hash value foreach (byte b in hash) { hashPassword.Append(b.ToString("X2")); } HashSalt hashSalt = new HashSalt { Hash = hashPassword.ToString(), Salt = salt }; return(hashSalt); }
public void CreateSaltedHashShouldInvalid() { HashSalt res = _saltHashHelper.GenerateSaltedHash(64, "Jason"); res.Hash += " "; Assert.False(_saltHashHelper.VerifyStr("Jason", res)); }
public void TestGenerateSaltedHash() { HashSalt hashSalt = encryptionService.GenerateSaltedHashPassword(storedSalt, "Test12345677"); HashSalt hashSalt1 = encryptionService.GenerateSaltedHashPassword(storedSalt, "Test12345677"); Assert.AreEqual(hashSalt.Hash.GetHashCode(), hashSalt1.Hash.GetHashCode()); }
public IActionResult ResetPassword([Bind("password, passwordValidation")] ResetPassword model) { if (ModelState.IsValid) { string email = TempData["Email"].ToString(); if (model.password != model.passwordValidation) { ModelState.AddModelError("PasswordResetError", "De ingevulde wachtwoorden zijn niet gelijk aan elkaar"); return(View()); } else { var userData = db.ProfileData.Where(e => e.Email == email).FirstOrDefault(); if (userData != null) { HashSalt newPassword = HashSalt.GenerateHashSalt(16, model.password); var userCredentials = db.AccountData.Where(user => user.ProfileId == userData.Id).FirstOrDefault(); userCredentials.Hash = newPassword.hash; userCredentials.Salt = newPassword.salt; db.SaveChanges(); return(RedirectToAction("ResetPasswordConfirmation")); } else { return(RedirectToAction("ForgotPassword")); } } } else { return(View()); } }
public IActionResult ChangePassword([FromBody] ChangePassword request) { try { string idUser = User.Claims.Where(c => c.Type.Equals(ClaimTypes.PrimarySid)).FirstOrDefault().Value; SystemUser user = _unitOfWork.User.GetById(int.Parse(idUser)); if (user != null) { SystemUser _user = _unitOfWork.User.ValidateUserPassword(user.Login, request.Password); if (_user != null) { // Actualizamos la contraseña _user.Password = request.NewPassword; _user.ChangePassword = false; HashSalt salt = new HashSalt(); salt = PasswordUtil.GenerateSaltedHash(32, _user.Password); _user.Password = salt.Hash; _user.Help = salt.Salt; return(Ok(_unitOfWork.User.Update(_user))); } else { return(StatusCode(500, "La clave ingresada no corresponde a la clave del usuario")); } } return(StatusCode(500, "No se encuentra el usuario")); } catch (Exception ex) { return(StatusCode(500, "Internal server error: " + ex.Message)); } }
private static void Register() { Console.Write("\nFirst Name: "); string firstName = Console.ReadLine(); Console.Write("Last Name: "); string lastName = Console.ReadLine(); Console.Write("Email: "); string email = Console.ReadLine(); Console.Write("Password: "******"Registration Successful! Please login to continue", ConsoleColor.Green); }
public async Task <dynamic> ChangePassword([FromBody] ValidateLoginUsersAddRequest validateloginuser) { UpdateLoginUsersResponse registrationResponse = new UpdateLoginUsersResponse(); var response = await _cloudantService.GetAllAsync(DBNames.loginusers.ToString()); BulkData loginusers = JsonConvert.DeserializeObject <BulkData>(response); var UpdatedLoginDetails = loginusers.rows.FirstOrDefault(a => a.doc.Username == validateloginuser.Username); HashSalt hashSalt = Helper.GenerateSaltedHash(64, validateloginuser.Password); LoginUsers loginuser = new LoginUsers(); loginuser.Username = UpdatedLoginDetails.doc.Username; loginuser.Password = hashSalt.Hash; loginuser.Passwordsalt = hashSalt.Salt; loginuser._id = UpdatedLoginDetails.doc._id; loginuser.Id = UpdatedLoginDetails.doc.Id; loginuser.EmailID = UpdatedLoginDetails.doc.EmailID; loginuser.Type = UpdatedLoginDetails.doc.Type; loginuser._rev = UpdatedLoginDetails.doc._rev; if (_postUserLoginProcessor != null) { return(await _putUserLoginProcessor.PutExistingUserRecord(loginuser, _cloudantService)); } else { return(new string[] { "No database connection" }); } }
//public async Task<UpdateLoginUsersResponse> Post([FromBody]LoginUsersAddRequest loginuser) public async Task <dynamic> Post([FromBody] LoginUsersAddRequest loginuser) { UpdateLoginUsersResponse registrationResponse = new UpdateLoginUsersResponse(); var response = await _cloudantService.GetAllAsync(DBNames.loginusers.ToString()); BulkData loginusers = JsonConvert.DeserializeObject <BulkData>(response); var IsUserExist = loginusers.rows.FirstOrDefault(a => a.doc.Username == loginuser.Username); if (IsUserExist == null) { if (_postUserLoginProcessor != null) { //return await _postUserLoginProcessor.PostNewUserRecord(loginuser, _cloudantService); HashSalt hashSalt = Helper.GenerateSaltedHash(64, loginuser.Password); loginuser.Password = hashSalt.Hash; loginuser.Passwordsalt = hashSalt.Salt; _postUserLoginProcessor.PostNewUserRecord(loginuser, _cloudantService); return(new string[] { "SUCCESS" }); } else { //return new UpdateLoginUsersResponse(); return(new string[] { "No database connection" }); } } else { return(new string[] { "USER_ALREADY_EXIST" }); } }
public static Result CreateSaveData(this FileSystemClient fs, TitleId applicationId, UserId userId, TitleId ownerId, long size, long journalSize, HashSalt hashSalt, uint flags) { return(fs.RunOperationWithAccessLog(LocalAccessLogMode.System, () => { IFileSystemProxy fsProxy = fs.GetFileSystemProxyServiceObject(); var attribute = new SaveDataAttribute { TitleId = applicationId, UserId = userId, Type = SaveDataType.SaveData }; var createInfo = new SaveDataCreateInfo { Size = size, JournalSize = journalSize, BlockSize = 0x4000, OwnerId = ownerId, Flags = flags, SpaceId = SaveDataSpaceId.User }; var metaInfo = new SaveMetaCreateInfo { Type = SaveMetaType.Thumbnail, Size = 0x40060 }; return fsProxy.CreateSaveDataFileSystemWithHashSalt(ref attribute, ref createInfo, ref metaInfo, ref hashSalt); }, () => $", applicationid: 0x{applicationId.Value:X}, userid: 0x{userId}, save_data_owner_id: 0x{ownerId.Value:X}, save_data_size: {size}, save_data_journal_size: {journalSize}, save_data_flags: 0x{flags:x8}")); }
public ActionResult <UserResponse> GetById([FromRoute] int id) { var authHeader = Request.Headers["Authorization"]; if (String.IsNullOrEmpty(authHeader).Equals(false) && authHeader.ToString().Contains("Basic")) { StringValues encodedUsernamePassword = authHeader.ToString().Remove(0, 5); var usernamePassword = Convert.FromBase64String(encodedUsernamePassword); string decoded = Encoding.UTF8.GetString(usernamePassword); var splitDecodedUnPwd = decoded.Split(":"); var userQueryUsername = _users.Where(splitDecodedUnPwd[0]); // if no user with username is found then return var getHashedPassword = userQueryUsername.HashedPassword; var getUserSalt = userQueryUsername.Salt; var decodedPassword = splitDecodedUnPwd[1]; var decodedPasswordHashed = HashSalt.HashPassword(decodedPassword, getUserSalt); if (getHashedPassword.Equals(decodedPasswordHashed) && id.Equals(userQueryUsername.Id)) { var user = _users.GetById(userQueryUsername.Id); return(new UserResponse(user)); } else { return(Unauthorized("bad login")); } } else { // should be a 400 bad request throw new Exception("The authorization header is either empty or isn't Basic."); } }
public ActionResult <CustomerHelper> Index(CustomerHelper helper) { CustomerDAO dao = new CustomerDAO(_db); Customer already = dao.GetByEmail(helper.email); if (already == null) { HashSalt hashSalt = GenerateSaltedHash(64, helper.password); helper.password = ""; // don’t need the string anymore Customer dbUser = new Customer(); dbUser.Firstname = helper.firstname; dbUser.Lastname = helper.lastname; dbUser.Email = helper.email; dbUser.Hash = hashSalt.Hash; dbUser.Salt = hashSalt.Salt; dbUser = dao.Register(dbUser); if (dbUser.Id > 0) { helper.token = "customer registered"; } else { helper.token = "customer registration failed"; } } else { helper.token = "customer registration failed - email already in use"; } return(helper); }
public bool RegisterUser([FromBody] Object reg) { var jsonString = reg.ToString(); RegParams result = JsonConvert.DeserializeObject <RegParams>(jsonString); User existUser = UserRepo.GetUser(result.Email); // User doesn't exist so create account if (existUser == null) { HashSalt hashSalt = LoginService.GenerateSaltedHash(10, result.Password); var user = new User { Name = result.Name, Email = result.Email, Password = hashSalt.Hash, SendEmail = result.SendEmail == "yes" ? true : false, Picks = new List <Pick>(), IsAdmin = false, Image = result.Image, Salt = hashSalt.Salt }; UserRepo.SaveUser(user); return(true); } return(false); }
public IActionResult Post([FromBody] ExternalUser externalUser) { int idUser = 0; if (!ModelState.IsValid) { return(BadRequest()); } using (var transaction = new TransactionScope()) { try { HashSalt salt = new HashSalt(); salt = PasswordUtil.GenerateSaltedHash(32, externalUser.Password); externalUser.Password = salt.Hash; externalUser.Help = salt.Salt; idUser = _unitOfWork.ExternalUser.Insert(externalUser); transaction.Complete(); } catch (Exception ex) { transaction.Dispose(); return(StatusCode(500, "Internal server error: " + ex.Message)); } } return(Ok(idUser)); }
public static object Response(SignInForm form, HashSalt hashSalt) { var identity = GetIdentity(form, hashSalt); if (identity == null) { return(null); } var now = DateTime.UtcNow; // создаем JWT-токен var jwt = new JwtSecurityToken( issuer: AuthOptions.ISSUER, audience: AuthOptions.AUDIENCE, notBefore: now, claims: identity.Claims, expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)), signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, username = identity.Name }; return(response); }
public void Execute(ApplicationUser request) { request.CreatedAt = DateTime.Now; HashSalt hashSalt = Password.GenerateSaltedHash(64, request.Password); request.Password = hashSalt.Hash; request.Salt = hashSalt.Salt; //Since user is registering for the first time on the app, his default role will be Developer request.RoleId = context.Roles.FirstOrDefault(x => x.Name == "Developer").Id; context.Add(request); context.SaveChanges(); //Send email SendEmailDto sendEmailDto = new SendEmailDto { SendTo = request.Email, Subject = "Successfull registration to Bug Tracker", Content = "Welcome to Bug Tracker" }; _emailSender.SendEmail(sendEmailDto); }
/// <summary> /// Attempts the admin login. /// </summary> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <returns></returns> public static bool AttemptAdminLogin(string username, string password) { try { var dba = new AdminDatabaseAccess(); var hashAndSalt = dba.AuthenticateAdminLogin(username); var t = new HashSalt(); t.makeHashSalt(password); var h = t.Hash; var s = t.Salt; if (hashAndSalt.Count == 2) { var hashSalt = new HashSalt(); var hash = hashAndSalt[0]; var salt = hashAndSalt[1]; var verify = hashSalt.verifyPassword(password, hash, salt); if (verify) { var information = dba.GetAdminsName(username); var loginCredentials = new Admin(information[0], information[1]); ActiveUser = new User(loginCredentials, int.Parse(username)) { IsAdmin = true }; return(true); } } return(false); } catch (Exception) { return(false); } }
/// <summary> /// Attempts the login. /// </summary> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <returns></returns> public static bool AttemptLogin(string username, string password) { var dba = new NurseDatabaseAccess(); var hashAndSalt = dba.AuthenticateLogin(username); //Just to get hash and salt to put into database. //var t = new HashSalt(); //t.makeHashSalt(password); //var h = t.Hash; //var s = t.Salt; if (hashAndSalt.Count == 2) { var hashSalt = new HashSalt(); var hash = hashAndSalt[0]; var salt = hashAndSalt[1]; var verify = hashSalt.verifyPassword(password, hash, salt); if (verify) { var information = dba.GetNursesName(username); var loginCredentials = new Nurse(information[0], information[1]); ActiveUser = new User(loginCredentials, int.Parse(username)); return(true); } } return(false); }
public void WhenCreatedWithBytes_ThenSetBytes() { byte[] bytes = { 1, 2, 3 }; var result = new HashSalt(bytes); Assert.That(result.Bytes, Is.SameAs(bytes)); }
public ActionResult Index(ASP_MVC_Skabelon.Models.LoginTable LogIndBruger) { //hvis modellen er udfyldt med fejl/mangler- send bruger tilbage til viwet ( her er samme side ) if (!ModelState.IsValid) { return(View(db.LoginTable.ToList())); } // Find ud af om der er match LoginTable BrugerMatch = new LoginTable(); //find brugeren baseret på brugernavn LoginTable BrugerNavnet = new LoginTable(); //Brugernavnet slåes op i tabellen BrugerNavnet = db.LoginTable.Where(b => b.username == LogIndBruger.username).FirstOrDefault(); //Hvis brugernavnet findes i tabellen if (BrugerNavnet != null) { // string passwordOgSalt = HashSalt.HashPassword(LogIndBruger.password, BrugerNavnet.salt); BrugerMatch = db.LoginTable.Where(b => b.username == LogIndBruger.username && b.password == passwordOgSalt).FirstOrDefault(); if (BrugerMatch != null) { // der blev fundet et match =login = session //der blev lavet en session - som er den vi "måler" på, om brugen skal have adgang til admin Session["BrugerSession"] = BrugerMatch.username; return(RedirectToAction("Index", "Admin")); // bruger sendes til startsiden på ADMIN } else { // brugermatch == null .....der var ikke noget match // her er mere sikerhed for logind da vi sletter sission hvis der noget forkert..... Session.Remove("BrugerSession"); ViewBag.Besked = "UPS! forkert brugernavn og/eller Password Prøv igen"; return(View(db.LoginTable.ToList())); // retun samme side med beskden. } } else { // brugermatch == null .....der var ikke noget match // her er mere sikerhed for logind da vi sletter sission hvis der noget forkert..... Session.Remove("BrugerSession"); ViewBag.Besked = "UPS! forkert brugernavn og/eller Password Prøv igen"; return(View(db.LoginTable.ToList())); // retun samme side med beskden. } }
private void hashBTN_Click(object sender, EventArgs e) { HashWithSaltResult hashResultSha256 = HashSalt.HashPassword(pwordTB.Text); #region Hash Password hashpwordTB.Text = hashResultSha256.Digest; saltTB.Text = hashResultSha256.Salt; #endregion }
public void ResetPassword([FromBody] Object password) { var jsonString = password.ToString(); PasswordString result = JsonConvert.DeserializeObject <PasswordString>(jsonString); HashSalt hashed = LoginService.GenerateSaltedHash(10, result.Password); string email = EncryptService.Decrypt(result.Encrypt, "astrophile"); UserRepo.UpdatePassword(hashed.Hash, email); UserRepo.UpdateSalt(hashed.Salt, email); }
private static HashSalt GenerateSaltedHash(string salt, string password) { Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, Convert.FromBase64String(salt), 10000, HashAlgorithmName.SHA512); string hashPassword = Convert.ToBase64String(rfc2898DeriveBytes.GetBytes(256)); HashSalt hashSalt = new HashSalt { Hash = hashPassword, Salt = salt }; return(hashSalt); }
public void GeneratePassword() { //Arange HashSalt generatedHashAndSalt = new HashSalt(); //Act generatedHashAndSalt = HashSalt.GenerateHashSalt(16, "password"); //Assert Assert.IsNotNull(generatedHashAndSalt); }
public void Register(RegisterModel register) { HashSalt hashSalt = Cryptography.GenerateSaltedHash(register.Password); register.Hash = hashSalt.Hash; register.Salt = hashSalt.Salt; register.ActiveStatus = true; register.CreateDate = DateTime.Now; context.UserProfiles.Add(register); context.SaveChanges(); }
// Serves as authentication public Account GetStatus(string nric, string password, string deviceID, string tokenID) { string salt = accountDAL.RetrieveSalt(nric); HashSalt hashSalt = GenerateSaltedHash(salt, password); Account account = accountDAL.RetrieveStatus(nric, hashSalt.Hash, deviceID, tokenID); Lockout(nric, account); return(accountDAL.RetrieveStatus(nric, hashSalt.Hash, deviceID, tokenID)); }
public HashSalt GenerateSaltedHashPassword(string salt, string password) { var saltBytes = Encoding.UTF8.GetBytes(salt); var provider = new RNGCryptoServiceProvider(); var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, saltBytes, 10000); var hashPassword = Convert.ToBase64String(rfc2898DeriveBytes.GetBytes(256)); HashSalt hashSalt = new HashSalt { Hash = hashPassword, Salt = salt }; return(hashSalt); }
public override int GetHashCode() { int hashcode = 157; unchecked { hashcode = (hashcode * 397) + PartitionInterval.GetHashCode(); hashcode = (hashcode * 397) + HashSalt.GetHashCode(); hashcode = (hashcode * 397) + ReplicationNumber.GetHashCode(); hashcode = (hashcode * 397) + TCollections.GetHashCode(SeedNodeList); } return(hashcode); }