protected void btnReset_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(txtNewPassword1.Text) || String.IsNullOrEmpty(txtNewPassword2.Text)) Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", "<script> alert('All fields are required.Thank you!'); </script>"); if (canChangePass) { Salt salt = new Salt(); string password1 = txtNewPassword1.Text; string password2 = txtNewPassword2.Text; if (txtNewPassword1.Text == txtNewPassword2.Text) { customer customerObj = new customer(); string role = "customer"; int result = customerObj.ResetPassword(email, null, password1, salt.ToString(),role); if (result == 0) lblMsg.Text = "The password you entered is incorrect!"; else if (result == 1) lblMsg.Text = "The password was changed successfully."; } } else lblMsg.Text = "You do not have authorization to access this email address."; }
protected void btnContinue_Click(object sender, EventArgs e) { string message = string.Empty; if (txtForgetEmail.Text != null) { string email = txtForgetEmail.Text; customer customerObj = new customer(); if (customerObj.existCustomerByEmail(email)) { Salt generatedCode = new Salt(); Session["email"] = email; Session["role"] = "customer"; customerObj.insertGeneratedCode(generatedCode.ToString(), email); string emailFrom = "*****@*****.**"; string emailTo = email; string subject = "Reset password"; message = "You have requested to change your password. Click <a href='Client_ResetPassword.aspx?code='"+generatedCode+"''> here</a> to reset you password."; Email objEmail = new Email(); objEmail.SendMail(emailTo, emailFrom, subject, message); lblMsg1.Text = "The email was sent."; } else lblMsg1.Text = "This email is not connected to any account!"; } else { lblMsg1.Text = "Please fill the form with the new password"; } }
protected void btnRegister_Click(object sender, EventArgs e) { phoneNum = txtPhoneNum.Text; email = txtEmail.Text; description = txtDescription.Text; url = txtURL.Text; email = txtEmail.Text; sID = txtSiteID.Text; string password = txtPassword.Text; Salt salt = new Salt(); lblAPI.Text = ""; merchant m = new merchant(); APIkey = m.apiGenerator().ToString(); Boolean keyFound = m.checkAPIExist(APIkey); while (keyFound == true) { APIkey = m.apiGenerator().ToString(); keyFound = m.checkAPIExist(APIkey); } lblAPI.Text = APIkey; //construct customerInfo object to pass into webservice webmthod (registerSite) merchant newMerch = new merchant(txtGroupMember1.Text, txtGroupMember2.Text, phoneNum); //check if merchant exists by siteID and return either true or false depending on if //it has been added if (pxy.RegisterSite(sID, description, APIkey, email,password,Convert.ToString(salt), m.contactInfo(newMerch)) == false) { lblMerchantAdded.Text = "Merchant seems to already exist. Try again!"; } else lblMerchantAdded.Text = "Merchant Added Successfully. Please take note of your API Key!"; }
protected override void Dispose(bool disposing) { _derivedBytes.Salt = new byte[8]; _derivedBytes.Reset(); _salt = null; base.Dispose(disposing); }
protected void btnSaveChanges_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(txtCurrentEmail.Text) || String.IsNullOrEmpty(txtCurrentPassword.Text) || String.IsNullOrEmpty(txtNewPassword.Text)) Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", "<script> alert('All fields are required.Thank you!'); </script>"); SqlCommand pass = new SqlCommand(); DBConnect objDB = new DBConnect(); //string currentPassword = (string)pass.ExecuteScalar(); //if (currentPassword == txtCurrentPassword.Text) // { } //else // lblMsg.Text = "Please enter your current password again!"; Salt salt = new Salt(); string currentEmail = txtCurrentEmail.Text; string currentPassword = txtCurrentPassword.Text; string newPassword1 = txtNewPassword.Text; customer customerObj=new customer(); int result = customerObj.ResetPassword(currentEmail, currentPassword, newPassword1, salt.ToString(),role); if (result == 0) lblMsg.Text = "The password you entered is incorrect!"; else if (result == 1) lblMsg.Text = "The password was changed successfully."; // Response.Redirect("LoginPage.aspx"); }
/// <summary> Seperates the salt from the data provided </summary> public SaltedData(byte[] saltedData, Salt.Size szSalt) { byte[] salt = Check.ArraySize(new byte[(int)szSalt / 8], 8, 64); Array.Copy(saltedData, 0, salt, 0, salt.Length); _salt = new Salt(salt, false); _data = new byte[saltedData.Length - salt.Length]; Array.Copy(saltedData, salt.Length, _data, 0, _data.Length); }
public override void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { var container = server.Container; if (container == null) { throw new Exception("Cannot access container"); } if (context.PreparedParameters == null) { context.PreparedParameters = RequestParameters.Create(context); } var certId = context.PreparedParameters.Get("cert"); if (string.IsNullOrWhiteSpace(certId)) { throw new ArgumentException("Empty certificate fingerprint"); } var hostConfigProvider = container.Get<IHostConfigProvider>(); if (hostConfigProvider == null) { throw new Exception("Cannot resolve server role"); } var hostConfig = hostConfigProvider.GetConfig(); if (hostConfig == null) { throw new Exception("Cannot resolve server role"); } var definition = hostConfig.Definition; if (definition == null) { throw new Exception("Cannot resolve server role"); } var caAttr = definition.Attr("ca"); if (!string.IsNullOrWhiteSpace(caAttr) && caAttr.To<bool>()) { lock (Sync) { Salt saltObj; if (Salts.ContainsKey(certId)) { saltObj = Salts[certId]; if (saltObj.Expire <= DateTime.UtcNow) { saltObj = new Salt { Value = Guid.NewGuid().ToString(), Expire = DateTime.UtcNow.AddHours(1) }; Salts[certId] = saltObj; } } else { saltObj = new Salt { Value = Guid.NewGuid().ToString(), Expire = DateTime.UtcNow.AddHours(1) }; Salts[certId] = saltObj; } context.Finish("\"" + saltObj.Value + "\""); CleanUpExpiredSaltsInternal(); return; } } var caProxy = container.Get<ICaWrapper>(); if (caProxy == null) { throw new Exception("Cannot access CA proxy"); } context.ContentType = MimeHelper.JSON; var salt = caProxy.GetSalt(certId); context.Finish(salt); }
public void TestSaltCopy() { Salt s = new Salt(); byte[] bytes = new byte[s.Length]; s.CopyTo(bytes, 0); Assert.AreEqual(s.ToArray(), bytes); Assert.AreEqual(s.GetHashCode(), Salt.FromBytes(bytes).GetHashCode()); Salt strcpy = Salt.FromString(s.ToString()); Assert.AreEqual(s.ToArray(), strcpy.ToArray()); Assert.AreEqual(s.ToString(), strcpy.ToString()); Assert.AreEqual(s.GetHashCode(), strcpy.GetHashCode()); }
private Salt ParseSaltString(string salt) { Salt salt_struct = new Salt(); try { string[] salt_split = salt.Split(new char[] { '.' }, 2); salt_struct.Iterations = Int32.Parse(salt_split[0]); salt_struct.Text = salt_split[1]; } catch (Exception ex){ throw new Exceptions.InvalidSaltException(ex.Message); } return salt_struct; }
//public User Authenticate(string login, string password) //{ // throw new NotImplementedException(); //} public User Create(User user) { //throw new NotImplementedException(); _context.Users.Add(user); var salt = Salt.Create(); var hash = Hash.Create(user.Password, salt); user.Password = hash; _context.SaveChanges(); return(user); }
public async Task <ActionResult <UserAuth> > PostUserAuth(UserAuth userAuth) { var xx = _context.UserAuth.FirstOrDefault(x => x.Id == userAuth.Id); var message = userAuth.Password; var salt = Salt.Create(); var hash = Hash.Create(message, salt); xx.Salt = salt; xx.Password = hash; await _context.SaveChangesAsync(); return(CreatedAtAction("GetUserAuth", new { id = userAuth.Id }, userAuth)); }
public void TestSaltGetData() { Salt s = new Salt(); byte[] bytes = new byte[1024]; new Random().NextBytes(bytes); SaltedData sd = s.GetData(bytes); Assert.AreEqual(s, sd.Salt); Assert.AreEqual(bytes, sd.GetDataBytes()); sd = s.GetData(new MemoryStream(bytes)); Assert.AreEqual(s, sd.Salt); Assert.AreEqual(bytes, sd.GetDataBytes()); }
public string UpdateSalt(Guid id) { if (this.IsContainSalt(id)) { Salt upSalt = this.Salts.First(s => s.Id == id); upSalt.SaltString = this.GenerateSalt(); this.Entry <Salt>(upSalt).State = EntityState.Modified; SaveChanges(); return(upSalt.SaltString); } else { return(this.AddSalt(id)); } }
/// <summary> /// Extracts the hash iterations from the salt. /// </summary> /// <exception cref="FormatException">Salt has not the format {int}.{string}</exception> private void ExtractHashIterationAndHmac() { try { var content = Salt.Split('.'); //Get the hash iteration from the first index HashIterations = int.Parse(content[1], System.Globalization.NumberStyles.Number); HashAlgorithm = new HashAlgorithmName(content[0]); } catch (Exception) { throw new FormatException("The salt was not in an expected format of {string}.{int}.{string}"); } }
/// <inheritdoc /> public bool Equals(KeyDerivationConfiguration other) { if (ReferenceEquals(null, other)) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return(Salt.SequenceEqualShortCircuiting(other.Salt) && String.Equals(FunctionName, other.FunctionName, StringComparison.OrdinalIgnoreCase) && (FunctionConfiguration == null ? other.FunctionConfiguration == null : FunctionConfiguration.SequenceEqualShortCircuiting(other.FunctionConfiguration))); }
public override int GetHashCode() { unchecked { var hashCode = Hash != null ? Hash.GetHashCode() : 0; hashCode = (hashCode * 397) ^ (Salt != null ? Salt.GetHashCode() : 0); hashCode = (hashCode * 397) ^ Iterations; hashCode = (hashCode * 397) ^ Prf.GetHashCode(); return(hashCode); } }
public IActionResult OnPostChangePassword([Bind("Id, Password, PasswordCheck")] ChangePasswordRequest changePasswordRequest) { if (!ModelState.IsValid) { return(Page()); } if (!_auth) { return(Unauthorized()); } using (var db = new LiteDatabase(@"movieReservation.db")) { var col = db.GetCollection <User>("users"); var maybeUser = col.FindOne(x => x.Id == changePasswordRequest.Id); if (maybeUser == null) { Error = "Gebruiker niet gevonden."; return(Page()); } if (!_auth.CanEdit(maybeUser)) { Error = "U kunt deze gebruiker niet bewerken."; return(Page()); } // Hash the password var salt = Salt.Create(); var hash = Hash.Create(changePasswordRequest.Password, salt); // Update the user maybeUser.HashPassword = hash; maybeUser.HashSalt = salt; var updated = col.Update(maybeUser); if (!updated) { Error = "Kon wachtwoord niet veranderen."; return(Page()); } } Success = "Wachtwoord veranderd."; return(Page()); }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } User = await _context.User.Where(s => s.UserName == loginData.UserName).Where(s => s.UserStatus == "Active") .FirstOrDefaultAsync(); if (User != null) { if (Hash.Validate(loginData.Password, Salt.Generate(loginData.UserName), User.UserPassword)) { SuccessMessage = $"User {User.UserName} logged in successfully!"; HttpContext.Session.Clear(); HttpContext.Session.SetString("_username", User.UserName); HttpContext.Session.SetString("_usertype", User.UserType); switch (User.UserType) { case "Student": return(RedirectToPage("/Student/Index")); case "Supervisor": return(RedirectToPage("/Supervisor/Index")); case "Coordinator": return(RedirectToPage("/Coordinator/Index")); default: return(RedirectToPage("/Account/Login")); } } else { ErrorMessage = $"{User.UserName} fail to log in."; } } else { ErrorMessage = $"{loginData.UserName} does not exist."; } return(RedirectToPage("/Account/Login")); }
public ActionResult Create(String nmObjeto, String txDescricao, String txUrl, String txUrlPoster, List <InteresseVM> tags) { try { if (tags == null || tags.Count == 0) { return(new HttpStatusCodeResult(HttpStatusCode.NotAcceptable, "É necessário selecionar ao menos 1 tema para o vídeo")); } Usuario usuarioLogado = AccountFacade.GetLoggedInUser(); List <Objeto> objetos = (new CoeusProjectContext()).Objetos.Where(o => o.IdUsuario == usuarioLogado.IdUsuario).Decrypt(); if (objetos.Where(o => o.NmObjeto == nmObjeto).Count() > 0) { return(new HttpStatusCodeResult(HttpStatusCode.OK)); } Video video = new Video() { Objeto = new Objeto() { IdUsuario = usuarioLogado.IdUsuario, Salt = Salt.GetSalt(), NmObjeto = nmObjeto, TxDescricao = txDescricao }, TxUrl = txUrl, TxUrlPoster = (new FileController()).FormatPoster(txUrlPoster) }; video.Objeto.Temas = new List <Tema>(); foreach (InteresseVM interesse in tags) { video.Objeto.Temas.Add(_context.Temas.Where(t => t.NmTema == interesse.NmInteresse).FirstOrDefault()); } _context.Videos.Add(video.Encrypt(_context)); _context.SaveChanges(); return(new HttpStatusCodeResult(HttpStatusCode.OK)); } catch (Exception ex) { return(new HttpStatusCodeResult(HttpStatusCode.NotAcceptable, ErrorFacade.GetErrorMessage(ex))); } }
public void TestSaltedDataStream() { Salt s = new Salt(Salt.Size.b64); byte[] testData = new byte[8]; byte[] test1 = new SaltedData(s, testData).ToArray(); Assert.AreEqual(16, test1.Length); byte[] test2 = IOStream.ReadAllBytes(new SaltedData(s, testData).ToStream()); Assert.AreEqual(16, test2.Length); byte[] test3 = IOStream.ReadAllBytes(SaltedData.CombineStream(s, new MemoryStream(testData))); Assert.AreEqual(16, test3.Length); Assert.AreEqual(test1, test2); Assert.AreEqual(test1, test3); Assert.AreEqual(test2, test3); }
private byte[] UnwrapMasterKeyData() { if (_keyEncryptingKey == null) { return(new byte[0]); } byte[] saltBytes = new byte[_keyEncryptingKey.DerivedKey.Size / 8]; Array.Copy(GetDataBlockBytesReference(), WRAP_SALT_OFFSET, saltBytes, 0, saltBytes.Length); Salt salt = new Salt(saltBytes); KeyWrap keyWrap = new KeyWrap(salt, KeyWrapIterations, KeyWrapMode.Specification); ICrypto crypto = _cryptoFactory.CreateCrypto(_keyEncryptingKey.DerivedKey, null, 0); byte[] wrappedKeyData = GetKeyData(crypto.BlockLength, _keyEncryptingKey.DerivedKey.Size / 8); return(keyWrap.Unwrap(crypto, wrappedKeyData)); }
public string GetAuthToken(HttpContext httpContext) { var userId = httpContext.User.FindFirst (claim => claim.Type == ClaimTypes.NameIdentifier) .Value; byte[] salt = Salt.GenerateSalt(); string authToken = System.Guid.NewGuid().ToString("N"); string hashedAuthToken = Hash.Compute(authToken, salt); hashedAuthToken = TrimToken(hashedAuthToken); UserResult userResult = UserProcessor.FindByField("id", userId).SingleOrDefault(); ApiSessionResult sessionResult = CreateApiSession(userResult, hashedAuthToken); return(sessionResult.AuthToken); }
public float originalCreatureSpeed; // to reassign it on trigger exit. That happend on creatures script method // Slows enemies' movement speed AND attack speed void OnTriggerEnter2D(Collider2D creature) { creatureMovement = creature.gameObject.GetComponent <MonsterMovement>(); slowEffect = gameObject.GetComponentInParent <Salt>(); creatureStats = creature.gameObject.GetComponent <ICreature>(); if (creature.tag == "Enemy") { creatureMovement.speed -= creatureMovement.speed * slowEffect.SlowEffect; creatureStats.currentState = ICreature.CreatureState.SLOWED; Debug.Log("SLOWED SPEED: " + creatureMovement.speed); } }
public static void TestMethodsEtc() { Salt salt = null; Assert.DoesNotThrow(() => { salt = new Salt(0); Assert.That(salt.Length, Is.EqualTo(0), "As a special case, zero length salt is supported - equivalent to no salt."); salt = new Salt(128); Assert.That(salt.Length, Is.EqualTo(16), "The length should be what was asked for."); Assert.That(salt.GetBytes(), Is.Not.EquivalentTo(new byte[16]), "A random salt is not likely to be all zeros."); salt = new Salt(192); Assert.That(salt.Length, Is.EqualTo(24), "The length should be what was asked for."); Assert.That(salt.GetBytes(), Is.Not.EquivalentTo(new byte[24]), "A random salt is not likely to be all zeros."); salt = new Salt(256); Assert.That(salt.Length, Is.EqualTo(32), "The length should be what was asked for."); Assert.That(salt.GetBytes(), Is.Not.EquivalentTo(new byte[32]), "A random salt is not likely to be all zeros."); salt = new Salt(new byte[16]); Assert.That(salt.GetBytes(), Is.EquivalentTo(new byte[16]), "A salt with all zeros was requested."); salt = new Salt(new byte[24]); Assert.That(salt.GetBytes(), Is.EquivalentTo(new byte[24]), "A salt with all zeros was requested."); salt = new Salt(new byte[32]); Assert.That(salt.GetBytes(), Is.EquivalentTo(new byte[32]), "A salt with all zeros was requested."); salt = new Salt(new byte[0]); Assert.That(salt.Length, Is.EqualTo(0), "As a special case, zero length salt is supported - equivalent to no salt."); } ); Assert.Throws <ArgumentNullException>(() => { salt = new Salt(null); }); Assert.Throws <ArgumentOutOfRangeException>(() => { salt = new Salt(-128); }); }
static void Main(string[] args) { Console.WriteLine("Select an option:"); Console.WriteLine("1. Create your own key"); Console.WriteLine("2. Randomly generate key"); Console.WriteLine("Enter your choice: "); int input = Console.Read(); char choice = Convert.ToChar(input); switch (choice) { case '1': Console.Write("Type in your key: ", Console.ReadLine()); string key = Key.createKey(Console.ReadLine()); Console.Write("Write your key pass: "******"hash: " + hash); Key.Verify(key, keyPass); Console.Write("HashCheck Type your password: "******"Write your key pass: "******"2dskfsdkl"; demo.DemoMain(); break; } Console.ReadKey(); }
public async Task <ActionResult <MemberResponse> > PostMember(RegisterRequest request) { // check if member with that email address already exists if (_context.Members.Any(m => m.Email == request.Email && m.CreationKey == null)) { return(BadRequest("You already have an account using that email address!")); } Member member; // update using CreationKey if (request.CreationKey != null) { member = _context.Members.FirstOrDefault(m => m.CreationKey == request.CreationKey); if (member == null) { return(NotFound("Invalid creation key!")); } member.CreationKey = null; } else { // add new member member = new Member(); } member.Email = request.Email; member.FirstName = request.FirstName; member.LastName = request.LastName; member.Salt = Salt.Create(); member.Password = Hash.Create(request.Password, member.Salt); if (request.CreationKey != null) { _context.Entry(member).State = EntityState.Modified; } else { _context.Members.Add(member); } await _context.SaveChangesAsync(); return(Ok(ToMemberResponse(member))); }
/// <summary> /// Implements <seealso cref="IDisposable.Dispose()"/> /// </summary> public void Dispose() { // Clear data try { Password.TryClear(clearAfterUse: true); Salt.TryClear(clearAfterUse: true); InitialVector.TryClear(clearAfterUse: true); PasswordIterations = 0; KeySize = 0; } catch (Exception) { // ignored } OnDisposing(); }
public bool SignUp(User user, string password) { if (UserRepository.GetUserByEmail(user.Email) != null) { throw new ApplicationException("User with same email is exist"); } if (UserRepository.GetUserByUserName(user.UserName) != null) { throw new ApplicationException("User with same user name is exist"); } var salt = Salt.Create(); var hash = AuthenticationHelper.Create(password, salt); user.Hash = hash; user.Salt = salt; UserRepository.Save(user); return(true); }
public async Task <ActionResult> PostUser([FromBody] int id, string password, string token) { var user = await _context.User.FindAsync(id); if (UserExists(id) && user.Token == token) { var passwordSalt = new Salt(); string passwordHash = Hash.Create(user.Password, passwordSalt.ToString()); user.Password = passwordHash; await _context.SaveChangesAsync(); return(Ok()); } else { return(BadRequest()); } }
private void ButtonOK_Click(object sender, EventArgs e) { if (CheckPassword()) { string password = Program.CurrentEmployee.Password; Program.CurrentEmployee.Password = Salt.Encrypt(txt_NewPassword.Text.Trim()); if (new EmployeeDao().UpdatePWD(Program.CurrentEmployee)) { MsgBox.ShowInfo("密码修改成功"); this.DialogResult = DialogResult.Yes; this.Close(); } else { MsgBox.ShowInfo("密码修改失败"); } } }
public async Task <bool> CreateUser(UserVM user) { var usr = await dbContext.Users.Where(o => o.IsDeleted == false && o.UserName == user.UserName).FirstOrDefaultAsync(); if (usr != null) { user.IsUserNameExists = true; return(false); } else { var userObj = mapper.Map <User>(user); userObj.SaltValue = Salt.Create(); userObj.PasswordHash = Hash.Create(userObj.PasswordHash, userObj.SaltValue); dbContext.Users.Add(userObj); return(await dbContext.SaveChangesAsync() > 0 ? true : false); } }
public void AddIngredientDoesNotRemoveIngredients() { //Arrange IRecipe recipe = new Bacon(null, DEFAULT_UNIT_SIZE); //Assert bool containsBacon = recipe.printRecipe().ToLower().Contains("bacon"); Assert.IsTrue(containsBacon); //Act recipe = new Salt(recipe, DEFAULT_UNIT_SIZE); //Assert containsBacon = recipe.printRecipe().ToLower().Contains("bacon"); bool containsSalt = recipe.printRecipe().ToLower().Contains("salt"); Assert.IsTrue(containsBacon); Assert.IsTrue(containsSalt); }
public async Task Save_User() { var expectedUser = new User( UserId.NewUserId(), new Name("name"), new Email("*****@*****.**"), new Password("pass"), new PasswordSalt(Salt.Create())); var sut = new UserRepository(_fixture.UserManagementDataContext); await sut.SaveAsync(expectedUser, _cancellationToken); await sut.CommitChangesAsync(_cancellationToken); var actualUser = await sut.SelectByEmailAsync(expectedUser.Email, _cancellationToken); actualUser.Should().BeEquivalentTo(expectedUser); }
static void Main(string[] args) { // var connect = new DatabaseConnection(); string senha = "1"; while (senha != "0") { Console.WriteLine("Qual a senha que deseja encriptar? "); senha = Console.ReadLine(); var hash = Hash.GenerateHash(senha); var salt = Salt.GenerateSalt(); var encrypt = Program.JoinHashSalt(salt, hash); Console.WriteLine($"SENHA: {Convert.ToBase64String(hash)}"); Console.WriteLine($"SALT: {Convert.ToBase64String(salt)}"); Console.WriteLine($"ENCRYPT FINAL: {Convert.ToBase64String(encrypt)}"); } }
public async Task <ICommandResult> Handle(AddUserCommand request, CancellationToken cancellationToken) { var registeredUser = await _userRepository.SelectByEmailAsync(request.Email, cancellationToken); if (registeredUser.Exists()) { return(new AddUserCommandResult(registeredUser)); } var salt = Salt.Create(); var hash = Hash.Create(request.Password.Value, salt); var userEntity = _userFactory.NewUser(request.Name, request.Email, new Password(hash), new PasswordSalt(salt)); var user = await _userRepository.SaveAsync(userEntity, cancellationToken); await _userRepository.CommitChangesAsync(cancellationToken); return(new AddUserCommandResult(user)); }
public CommandResult RegisterAdmin(UserRegisterAdminCommand command, string userIdentity) { var exist = _repository.Exists(command.Username); if (exist) { AddNotification("Já existe um usuario cadastrado com esse nome. "); } var user = new UserAuth(command.Username, command.Password, command.Role, command.Active); AddNotifications(user); if (Invalid) { return(new CommandResult(false, GroupNotifications.Group(Notifications), command)); } // Add Hash e Salt var salt = Salt.Create(); var hash = Hash.Create(user.Password, salt); if (!Hash.Validate(user.Password, salt, hash)) { AddNotification("Erro na geração do Hash. "); } user.AddHash(hash, Convert.ToBase64String(salt)); _repository.Register(user); var log = new AccessLog( "Register", DateTime.Now, userIdentity, "UserAuth", $"Nome usuario registrado: {command.Username}"); _log.Register(log); user.HidePassword(); return(new CommandResult(true, "Cadastro realizado. ", user)); }
/// <summary> /// Responsável por efetuar o login do usuário na aplicação /// </summary> /// <param name="login"> Usuário de autenticação</param> /// <param name="senha"> Senha do usuário para autenticação</param> /// <returns>Informações básicas para autenticar o usuário</returns> public UsuarioAutenticado Login(string login, string senha) { var entidadeLocalizada = _dbContext.Usuarios.Where(data => data.Login.Equals(login, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); if (entidadeLocalizada == null) { throw new RegistroNaoEncontradoException("Usuário não localizado."); } JavaScriptSerializer js = new JavaScriptSerializer(); byte[] SaltDeSerializado = js.Deserialize <byte[]>(entidadeLocalizada.Salt); Salt _Salt = new Salt(_LengthSalt); byte[] _senha = _Salt.GenerateDerivedKey(_LengthSalt, Encoding.UTF8.GetBytes(senha), SaltDeSerializado, 5000); if (entidadeLocalizada.Senha != _Salt.getPassword(_senha)) { throw new RegistroNaoEncontradoException("Usuário não localizado."); } if ((!entidadeLocalizada.Verificado.HasValue) && (!entidadeLocalizada.Verificado.Value)) { throw new UsuarioNaoVerificadoException("Usuário não verificado."); } if ((entidadeLocalizada.Bloqueado.HasValue) && (entidadeLocalizada.Bloqueado.Value)) { throw new UsuarioBloqueadoException("Usuário bloqueado."); } if (entidadeLocalizada.DataCancelamento.HasValue) { throw new RegistroNaoEncontradoException("Usuário cancelado."); } return(new UsuarioAutenticado() { ID = entidadeLocalizada.ID, Nome = entidadeLocalizada.Nome, Email = entidadeLocalizada.Email, Claim = entidadeLocalizada.Claim, TimeZone = entidadeLocalizada.TimeZone }); }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } var username = HttpContext.Session.GetString("_username"); User = await _context.User.Where(s => s.UserName == username) .FirstOrDefaultAsync(); if (User != null) { if (Hash.Validate(changeData.Password, Salt.Generate(username), User.UserPassword)) { if (changeData.NewPassword.Equals(changeData.ConfirmPassword)) { var newHashedPassword = Hash.Generate(changeData.NewPassword, Salt.Generate(username)); User.UserPassword = newHashedPassword; User.DateModified = DateTime.Now; SuccessMessage = $"Password changed for " + username; await _context.SaveChangesAsync(); } else { ErrorMessage = $"The two passwords do not match. "; } } else { ErrorMessage = $"The existing password is incorrect. "; } } else { ErrorMessage = $"User {username} does not exist."; } return(RedirectToPage("/Coordinator/Management/Index")); }
public Blake2BConfig Clone() { var result = new Blake2BConfig(); result.OutputSizeInBytes = OutputSizeInBytes; if (Key != null) { result.Key = (byte[])Key.Clone(); } if (Personalization != null) { result.Personalization = (byte[])Personalization.Clone(); } if (Salt != null) { result.Salt = (byte[])Salt.Clone(); } return(result); }
// Client Constructor, salt not generated by client public Srp6(byte[] identityHash, String modulus, int generator, String salt, string initialVector = "OFRna73m*aze01xY") : this(initialVector, modulus, generator, identityHash) { // This SRP6 instance is a client instance IsServerInstance = false; // Convert the salt string to a BigInteger Salt = BigIntegerExtensions.CreateBigInteger(salt, 16); // Set the salted identity hash SaltedIdentityHash = Salt.CreateSaltedIdentityHash(identityHash); // Generate a pseudo prime to use for the private key PrivateKey = BigIntegerExtensions.GeneratePseudoPrime(128, 100, new Random()); // g^a (mod N) PublicKey = Generator.ModPow(PrivateKey, Modulus); }
public void TestCreateSalt() { Salt s = new Salt(); Assert.AreEqual(32, s.Length); Assert.AreNotEqual(new byte[32], s.ToArray()); Salt s8 = new Salt(Salt.Size.b64); Assert.AreEqual(8, s8.Length); Assert.AreEqual(Salt.Size.b64, s8.BitSize); Salt s16 = new Salt(Salt.Size.b128); Assert.AreEqual(16, s16.Length); Assert.AreEqual(Salt.Size.b128, s16.BitSize); Salt s32 = new Salt(Salt.Size.b256); Assert.AreEqual(32, s32.Length); Assert.AreEqual(Salt.Size.b256, s32.BitSize); Salt s64 = new Salt(Salt.Size.b512); Assert.AreEqual(64, s64.Length); Assert.AreEqual(Salt.Size.b512, s64.BitSize); }
//private bool _verified; /* this is a debugging aid used to ensure all messages are signed or verified */ public Message(TransferState state, Guid transferId, RSAPublicKey key, Converter<Guid, Salt> sessionSecret) { _version = VersionHeader; _state = state; _transferId = transferId; _salt = new Salt(Salt.Size.b256); _protected = new MemoryStream(); _payload = new NonClosingStream(_protected); _hash = new HashStream(new SHA256Managed()); WriteHeader(_hash); Salt secret; if (!UsesSessionKey) { // Outer encryption is straight PKI based on the remote public key _payload = key.Encrypt(_payload); _hash.ChangeStream(_payload); // Preceed the message with a new, AES key secret = new Salt(Salt.Size.b256); _hash.Write(secret.ToArray(), 0, 32); } else { secret = sessionSecret(_transferId); Check.IsEqual(32, Check.NotNull(secret).Length); } AESCryptoKey sessionKey = new AESCryptoKey( // Prefix the key with the message's salt and compute a SHA256 hash to be used as the key Hash.SHA256(_salt.GetData(secret.ToArray()).ToStream()).ToArray(), // Compute an IV for this aes key and salt combination IV(secret, _salt) ); _payload = sessionKey.Encrypt(_payload); _hash.ChangeStream(_payload); }
public void TestSaltStream() { Salt s = new Salt(); Assert.AreEqual(s.ToArray(), IOStream.ReadAllBytes(s.ToStream())); }
private LocalHostKey(DataProtectionScope scope, Salt salt) : this(scope) { _salt = salt; }
public BytesToRead(Client client, int threadLimit, Guid transferId, Salt sessionKey, string location, StreamCache streams, long offset, int count) { _client = client; _transferId = transferId; _sessionKey = sessionKey; _location = location; _streams = streams; _offset = offset; _count = count; _throttle = new Semaphore(threadLimit, threadLimit, GetType().FullName); _throttle.WaitOne(); _aquired = true; }
private static void ReadHeader(Stream input, out int ver, out TransferState state, out Guid txid, out Salt salt) { ver = PrimitiveSerializer.Int32.ReadFrom(input); Check.Assert<InvalidDataException>(ver == VersionHeader); int istate = PrimitiveSerializer.Int32.ReadFrom(input); Check.Assert<InvalidDataException>(Enum.IsDefined(typeof(TransferState), istate)); state = (TransferState)istate; byte[] bytes = new byte[16]; Check.Assert<InvalidDataException>(bytes.Length == input.Read(bytes, 0, bytes.Length)); txid = new Guid(bytes); bytes = new byte[32]; Check.Assert<InvalidDataException>(bytes.Length == input.Read(bytes, 0, bytes.Length)); salt = Salt.FromBytes(bytes); }
/// <summary> /// Sets or changes the salt for this encryption key /// </summary> public LocalHostKey WithSalt(Salt salt) { return new LocalHostKey(_scope, salt); }
public void TestEquality() { Salt s = new Salt(); Salt scopy = Salt.FromBytes(s.ToArray()); Assert.AreEqual(s, scopy); Assert.IsTrue(s.Equals(scopy)); Assert.IsTrue(s.Equals((object)scopy)); Assert.IsTrue(s == scopy); Assert.IsFalse(s != scopy); Assert.AreEqual(s.GetHashCode(), scopy.GetHashCode()); scopy = new Salt(); Assert.AreNotEqual(s, scopy); Assert.IsFalse(s.Equals(scopy)); Assert.IsFalse(s.Equals((object)scopy)); Assert.IsFalse(s == scopy); Assert.IsTrue(s != scopy); Assert.AreNotEqual(s.GetHashCode(), scopy.GetHashCode()); }
private void TransferBytes(Guid transferId, Salt sessionKey, string location, long offset, byte[] bytes) { // STEP 3...n: Send a block of bytes using (Message req = new Message(TransferState.SendBytesRequest, transferId, _publicKey, s => sessionKey)) { req.Write(offset); req.Write(bytes); Stream response = SendPayload(req, location, req.ToStream(_privateKey)); using (Message rsp = new Message(response, _privateKey, s => sessionKey)) { Check.Assert<InvalidOperationException>(rsp.State == TransferState.SendBytesResponse); Check.Assert<InvalidOperationException>(rsp.ReadInt64() == offset); rsp.VerifySignature(_publicKey); } } }
private void ReadByteRange(Guid transferId, Salt sessionKey, string location, StreamCache streams, long offset, int count) { using (Message req = new Message(TransferState.DownloadBytesRequest, transferId, _publicKey, s=>sessionKey)) { req.Write(location); req.Write(offset); req.Write(count); Stream response = SendPayload(req, location, req.ToStream(_privateKey)); using (Message rsp = new Message(response, _privateKey, s=>sessionKey)) { Check.Assert<InvalidOperationException>(rsp.State == TransferState.DownloadBytesResponse); byte[] bytes = rsp.ReadBytes(100 * 1000 * 1024); Check.Assert<InvalidOperationException>(bytes.Length == count); rsp.VerifySignature(_publicKey); using(Stream io = streams.Open(FileAccess.Write)) { io.Seek(offset, SeekOrigin.Begin); io.Write(bytes, 0, count); } } } }
private void CompleteUpload(Guid transferId, Salt sessionKey, string location, Hash fullHash) { // STEP 4: Finalize the transfer using (Message req = new Message(TransferState.UploadCompleteRequest, transferId, _publicKey, s => sessionKey)) { req.Write(location); req.Write(fullHash.ToArray()); Stream response = SendPayload(req, location, req.ToStream(_privateKey)); using (Message rsp = new Message(response, _privateKey, s => sessionKey)) { Check.Assert<InvalidOperationException>(rsp.State == TransferState.UploadCompleteResponse); rsp.VerifySignature(_publicKey); } } }
public void TestSaltedDataWithSpecificSize() { Salt s = new Salt(Salt.Size.b64); byte[] testData = new byte[8]; new Random().NextBytes(testData); byte[] tmp; using (SaltedData sd = new SaltedData(s, testData)) { Assert.AreEqual(16, sd.Length); Assert.AreEqual(s, sd.Salt); Assert.AreEqual(testData, sd.GetDataBytes()); tmp = sd.ToArray(); Assert.AreEqual(16, tmp.Length); Assert.AreEqual(tmp, IOStream.ReadAllBytes(sd.ToStream())); } using (SaltedData sd = new SaltedData(s, new MemoryStream(testData))) { Assert.AreEqual(s, sd.Salt); Assert.AreEqual(testData, sd.GetDataBytes()); Assert.AreEqual(tmp, sd.ToArray()); } using (SaltedData sd = new SaltedData(tmp, Salt.Size.b64)) { Assert.AreEqual(s, sd.Salt); Assert.AreEqual(testData, sd.GetDataBytes()); Assert.AreEqual(tmp, sd.ToArray()); } }
private Salt BeginUpload(Guid transferId, string location, long length, out int maxMessageLength) { byte[] serverKeyBits; byte[] nonce = GetNonce(transferId, location, out serverKeyBits); Hash hnonce = Hash.SHA256(nonce); //STEP 2: Create and send session key Salt clientKeyBits = new Salt(Salt.Size.b256); Salt sessionSecret = SessionSecret(clientKeyBits, serverKeyBits); using (Message req = new Message(TransferState.UploadRequest, transferId, _publicKey, NoSession)) { req.Write(hnonce.ToArray()); req.Write(length); req.Write(location); req.Write(clientKeyBits.ToArray()); Stream response = SendPayload(req, location, req.ToStream(_privateKey)); using (Message rsp = new Message(response, _privateKey, s=>sessionSecret)) { Check.Assert<InvalidOperationException>(rsp.State == TransferState.UploadResponse); maxMessageLength = Check.InRange(rsp.ReadInt32(), 0, int.MaxValue); rsp.VerifySignature(_publicKey); } } return sessionSecret; }
private LocalHostKey(DataProtectionScope scope) { _scope = scope; _salt = null; }
public PasswordHashTests() { _salt = Salt.Generate(PasswordHash.DefaultSaltSize); _sut = new PasswordHash(Password,PasswordHash.DefaultIterations,_salt); }
public SaltyKey(Key key, Salt salt) { Key = key; Salt = salt; }
public BytesToSend(Client client, int threadLimit, Guid transferId, Salt sessionKey, string location, long offset, byte[] bytes) { _client = client; _transferId = transferId; _sessionKey = sessionKey; _location = location; _bytes = bytes; _offset = offset; _throttle = new Semaphore(threadLimit, threadLimit, GetType().FullName); _throttle.WaitOne(); _aquired = true; }
private byte[] IV(Salt secret, Salt salt) { // Long story, this has been a little difficult to finally settle upon an algorithm. // We know we don't want to the same value each time, and we prefer not to use only // the public salt. My biggest concern is not generating a IV value that interacts // with AES in a way that might divulge information unintentionally. Since we are // using the same values (salt+secret) to derive the IV this is a very real risk. // To mitigate this risk the primary interaction of secret in the derivation of this // value is compressed into a CRC of both the salt and secret. This value is then // masked with computations of salt to produce the 16 IV bytes needed. byte[] sbytes = salt.ToArray(); byte[] result = new byte[16]; // compute a mask from CRC32(salt + secret) int mask = new Crc32(_salt.GetData(secret.ToArray()).ToArray()).Value; // xor part of the mask with the sum of two salt bytes for (int i = 0; i < 16; i++) result[i] = (byte)((mask >> i) ^ (sbytes[i] + sbytes[i + 16])); return result; }