/// <summary> /// Salt and encript the given password. /// </summary> /// <param name="password"> </param> private void EncryptPassword(string password) { if (string.IsNullOrWhiteSpace(password)) throw new ArgumentNullException("password"); var cryptoService = new PBKDF2(); EncryptedPassword = cryptoService.Compute(password); Salt = cryptoService.Salt; }
PBKDF2 GetHasher() { PBKDF2 hasher = new PBKDF2 { PlainText = mDefaultPassword }; return hasher; }
public Password CreatePasswordData(string password) { byte[] saltBytes = new byte[hashBytesCount]; new CryptoRandom().NextBytes(saltBytes); string nextSalt = saltBytes.ToB64(); byte[] hashBytes = new PBKDF2(sha384Func, password, saltBytes, iterationCount) .GetBytes(hashBytesCount); var passwordData = new Password { NextLoginSalt = nextSalt, NextPasswordHash = hashBytes.ToB64() }; return(passwordData); }
/// <summary> /// hash the password /// </summary> /// <param name="password"></param> /// <returns></returns> private byte[] HashPassword(string password) { //Org.BouncyCastle.Crypto.Digests.Sha3Digest sha = new Org.BouncyCastle.Crypto.Digests.Sha3Digest(512); //this._Password = new byte[sha.GetByteLength()]; //sha.BlockUpdate(password.GetBytes(), 0, password.Length); //sha.DoFinal(this._Password, 0); //return this._Password; Blake2b hash = new Blake2b(512); //this._Password = new byte[sha.GetHashLength()]; //sha.Update(password); //sha.DoFinal(this._Password, 0); //return this._Password; PBKDF2 pbkdf = new PBKDF2(hash, this._PasswordIteration); return(pbkdf.Derive(password.GetBytes(), null, (this._PasswordIteration) * hash.GetHashLength())); }
public ActionResult Register(User user) { if (ModelState.IsValidField("Email") && ModelState.IsValidField("FirstName") && ModelState.IsValidField("LastName") && ModelState.IsValidField("PhoneNumber") && ModelState.IsValidField("ICNumber") && ModelState.IsValidField("Password")) { string password = user.Password; PBKDF2 PwdHash = new PBKDF2(password); string passwordhash = PwdHash.HashedPassword; SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MrtContext"].ConnectionString); SqlCommand cmd = new SqlCommand("spInsertUser", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Email", user.Email); cmd.Parameters.AddWithValue("@FirstName", user.FirstName); cmd.Parameters.AddWithValue("@LastName", user.LastName); cmd.Parameters.AddWithValue("@ICNumber", user.ICNumber); cmd.Parameters.AddWithValue("@PhoneNumber", user.PhoneNumber); cmd.Parameters.AddWithValue("@Password", passwordhash); cmd.Parameters.AddWithValue("@Roles", "User"); cmd.Parameters.AddWithValue("@RegistrationDateTime", DateTime.Now.ToString()); try { conn.Open(); cmd.ExecuteNonQuery(); return(RedirectToAction("Login")); } catch { return(View()); } finally { conn.Close(); } } else { return(View()); } }
public User ChangePassword(int userId, string password) { using (TransactionScope scope = new TransactionScope()) { var user = _context.Users.SingleOrDefault(m => m.Id == userId); if (user == null) { return(null); } ICryptoService cryptoService = new PBKDF2(); string passwordSalt = cryptoService.GenerateSalt(); string hashedPassword = cryptoService.Compute(password); user.Password = hashedPassword; user.PasswordSalt = passwordSalt; _context.SaveChanges(); scope.Complete(); return(user); } }
protected void btnGuardar_Click(object sender, EventArgs e) { try { string nombre = txtNombrePersona.Text.Trim(); string apellidos = txtApellidos.Text.Trim(); string usuario = txtUsuario.Text.Trim(); string contrasenna = txtContrasenna.Text.Trim(); int edad = int.Parse(txtEdad.Text.Trim()); string email = txtEmail.Text.Trim(); ICryptoService cryptoService = new PBKDF2(); string salt = cryptoService.GenerateSalt(); string contrasenaEncriptada = cryptoService.Compute(contrasenna); Persona objPersona = new Persona(); objPersona.nombrePersona = nombre; objPersona.apellidoPersona = apellidos; objPersona.usuario = usuario; objPersona.contrasenna = contrasenaEncriptada; objPersona.edad = edad; objPersona.salt = salt; objPersona.estado = 1; objPersona.idTipoPersona = 2; objPersona.email = email; try { db.Persona.InsertOnSubmit(objPersona); db.SubmitChanges(); } catch (Exception) { throw; } } catch { ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "alertaPassFail", "window.onload = function(){alert('Debe rellenar la solicitud');};", true); } }
public void TestDifferentIterationsProducesDifferentResults() { var hashes = new HashSet <string>(); string password = Guid.NewGuid().ToString("N"); byte[] salt; var hash1 = PBKDF2.ComputeHash(password, out salt); Assert.AreEqual(32, salt.Length, "Salt length"); Assert.AreEqual(32, hash1.Length, "Hash1 length"); for (int i = 0; i < 20; ++i) { byte[] hash2 = PBKDF2.ComputeHash(password, salt, 1000 + i); hashes.Add(Convert.ToBase64String(hash2)); } Assert.AreEqual(20, hashes.Count, "Number of unique hashes"); }
public static (byte[] pw, byte[] mk, byte[] ak, string reqpw) CreateAuthData003(StandardNoteAPI.APIResultAuthParams apiparams, string mail, string uip) { if (apiparams.pw_cost < 100000) { throw new StandardNoteAPIException($"Account pw_cost is too small ({apiparams.pw_cost})"); } var salt = StandardNoteCrypt.SHA256Hex(string.Join(":", mail, "SF", "003", apiparams.pw_cost.ToString(), apiparams.pw_nonce)); byte[] bytes = PBKDF2.GenerateDerivedKey(768 / 8, Encoding.UTF8.GetBytes(uip), Encoding.UTF8.GetBytes(salt), apiparams.pw_cost, PBKDF2.HMACType.SHA512); var pw = bytes.Skip(0 * (bytes.Length / 3)).Take(bytes.Length / 3).ToArray(); var mk = bytes.Skip(1 * (bytes.Length / 3)).Take(bytes.Length / 3).ToArray(); var ak = bytes.Skip(2 * (bytes.Length / 3)).Take(bytes.Length / 3).ToArray(); var reqpw = EncodingConverter.ByteToHexBitFiddleUppercase(pw).ToLower(); return(pw, mk, ak, reqpw); }
private WebUser CheckAuth(HttpListenerContext ctx) { HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)ctx.User.Identity; if (authCache.TryGetValue(identity.Name, out WebUser user)) { if (!PBKDF2.VerifyPassword(Util.Md5(identity.Password), user.PasswordHash)) { user = Core.Database.GetWebUser(identity.Name, identity.Password); if (user != null) { authCache.Remove(user.Username); authCache.Add(user.Username, user); Core.Database.UpdateLastSeen(user); } else { Logger.Log(LogLevel.Info, "User {0} ({1}): invalid login (cached/password mismatch)", identity.Name, ctx.Request.RemoteEndPoint.ToString()); } } } else { user = Core.Database.GetWebUser(identity.Name, Util.Md5(identity.Password)); if (user != null) { authCache.Add(user.Username, user); Core.Database.UpdateLastSeen(user); } else { Logger.Log(LogLevel.Info, "User {0} ({1}): invalid login (db/password mismatch)", identity.Name, ctx.Request.RemoteEndPoint.ToString()); } } if (user != null) { user.IPEP = ctx.Request.RemoteEndPoint; } return(user); }
public static bool Validate(string savedPasswordHash, string savedPasswordSalt, string plainTextPassword) { if (string.IsNullOrEmpty(savedPasswordHash)) { throw new ArgumentNullException("savedPasswordHash"); } if (string.IsNullOrEmpty(savedPasswordHash)) { throw new ArgumentNullException("savedPasswordSalt"); } if (string.IsNullOrEmpty(savedPasswordHash)) { throw new ArgumentNullException("plainTextPassword"); } var cryptoService = new PBKDF2(); var passwordHash = cryptoService.Compute(plainTextPassword, savedPasswordSalt); return(cryptoService.Compare(passwordHash, savedPasswordHash)); }
public ActionResult CambioPassword(UtenteCambioPasswordViewModel model) { if (base.ModelState.IsValid) { using (DatabaseContext db = new DatabaseContext()) { PersonaModel utente = base.Session["utente"] as PersonaModel; PBKDF2 crypto = new PBKDF2(); utente.Persona.PASSWORD = crypto.Compute(model.Password, utente.Persona.TOKEN_PASSWORD); db.Entry <PERSONA>(utente.Persona).State = EntityState.Modified; if (db.SaveChanges() > 0) { base.Session["utente"] = utente; base.TempData["salvato"] = true; } } } return(base.View(model)); }
public bool ValidatePassword(Guid userId, string password) { Password targetPassword = registeredPasswords[userId]; if (targetPassword == null) { throw new InvalidOperationException($"Password for user id '{ userId }' is not registered"); } byte[] saltBytes = targetPassword.NextLoginSalt.FromB64(); byte[] storedHashBytes = targetPassword.NextPasswordHash.FromB64(); byte[] passedHashBytes = new PBKDF2(sha384Func, password, saltBytes, iterationCount) .GetBytes(hashBytesCount); bool areEqual = Utils.ConstantTimeEqual(storedHashBytes, passedHashBytes); return(areEqual); }
protected void btn_newPassword_Click(object sender, EventArgs e) { ICryptoService cryptoService = new PBKDF2(); string password = txtPassword.Text; //save this salt to the database string PasswordSalt = cryptoService.GenerateSalt(); //save this hash to the database string hashedPassword = cryptoService.Compute(password); MembersTableAdapters.MembersTableAdapter taMember = new MembersTableAdapters.MembersTableAdapter(); taMember.UpdatePassword(hashedPassword, PasswordSalt, DateTime.Now, Convert.ToInt32(hfAutoID.Value)); taMember.Dispose(); string strMsg = "<p class=\"header2\">Password Changed</p><p>Now you can login with your new password.</p>"; strMsg += "<p style=\"text-align:right; margin-bottom:1px;\"><input type=button value=\"Log-In Now\" onclick=\"self.location.href='Login.aspx'\"></p><hr>"; litMsgBody.Text = strMsg; }
public ActionResult Recuperar(string correo, string password) { string constr = conexion; using (MySqlConnection con = new MySqlConnection(constr)) { string query = "select * from web_usuarios_login WHERE Cod_Usuario ='" + correo + "'"; using (MySqlCommand cmd = new MySqlCommand(query)) { cmd.Connection = con; con.Open(); using (MySqlDataReader sdr = cmd.ExecuteReader()) { while (sdr.Read()) { if (sdr.HasRows) { ICryptoService cryptoService = new PBKDF2(); Salt = cryptoService.GenerateSalt(); PasswordEncriptada = cryptoService.Compute(password); string constr1 = conexion; using (MySqlConnection Con1 = new MySqlConnection(constr1)) { Con1.Open(); MySqlCommand cmd1 = new MySqlCommand(bd + "web_actualiza_password", Con1); cmd1.CommandType = CommandType.StoredProcedure; cmd1.Parameters.AddWithValue("p_usuario", correo); cmd1.Parameters.AddWithValue("p_clave", PasswordEncriptada); cmd1.Parameters.AddWithValue("p_salt", Salt); cmd1.Parameters.AddWithValue("p_Password_Dsk", password); cmd1.ExecuteNonQuery(); Con1.Close(); } } } } con.Close(); } } return(RedirectToAction("../Login/Login")); }
private static void HashPasswordFromTestPBKDF(string passwordToHash, int numberOfIterations) { var sw = new Stopwatch(); sw.Start(); var hashedPassword = PBKDF2.HashPasswordWithPBKDF( Encoding.UTF8.GetBytes(passwordToHash), PBKDF2.GenerateSalt(), numberOfIterations ); sw.Stop(); Console.WriteLine(); Console.WriteLine($"Password to hash: {passwordToHash}"); Console.WriteLine($"Hashed Password: {Convert.ToBase64String(hashedPassword)}"); Console.WriteLine($"Iterations <{numberOfIterations}> | Elapsed Time: {sw.ElapsedMilliseconds}"); }
public static async Task <Customer> AuthenticateAsync(MainContext context, string userID, string password) { //var login = context.Logins.FirstOrDefault(x => x.UserID == userID); var login = await context.Logins.FirstOrDefaultAsync(x => x.UserID == userID); // If userID is not found or password does not match if (login == null || password == null || !PBKDF2.Verify(login.PasswordHash, password)) { login.AttemptLoginFailed(); context.SaveChanges(); return(null); } else { login.AttemptLoginSuccessful(); context.SaveChanges(); return(login.Customer); } }
/// <summary> /// Checks if the request carries a valid long-term cookie, and replaces it with a new valid cookie. /// If a hijack is performed, the response headers will be flushed. /// Callers should check the flush status after calling this method. /// </summary> /// <returns><c>True</c> if the long-term cookie is valid, <c>false</c> otherwise.</returns> /// <param name="context">The http context.</param> protected virtual async Task <bool> PerformLongTermLogin(IHttpContext context) { if (!UseLongTermCookieStorage || LongTermStorage == null) { return(false); } var longterm = context.Request.Cookies[AuthCookieName]; if (string.IsNullOrWhiteSpace(longterm)) { return(false); } var ltc = new LongTermCookie(longterm); if (!ltc.IsValid) { return(false); } var lts = await LongTermStorage.GetLongTermLoginAsync(ltc.Series); if (Utility.IsNullOrExpired(lts)) { return(false); } if (!PBKDF2.ComparePassword(ltc.Token, lts.Token)) { await LongTermStorage.DropAllLongTermLoginsAsync(lts.UserID, lts.Series); SetHijackError(context); await context.Response.FlushHeadersAsync(); return(false); } await PerformLoginAsync(context, lts.UserID, lts.Series, true); return(true); }
public static IEnumerable PBKDF2HashList(string text, string salt) { ICryptoService cryptoService = new PBKDF2(); ArrayList hashedText = new ArrayList(); string hash; if (salt == null) { hash = cryptoService.Compute(text, 16, 5000); salt = cryptoService.Salt; } else { hash = cryptoService.Compute(text, salt); } hashedText.Add(new HashedBytes(hash, salt)); return(hashedText); }
public byte[] Unwrap([ReadOnlyArray] byte[] encryptedCek, object key, uint cekSizeBits, JsonObject header) { var sharedPassphrase = Ensure.Type <string>(key, "Pbse2HmacShaWithAesKWKeyManagement management algorithm expectes key to be string."); byte[] sharedKey = Encoding.UTF8.GetBytes(sharedPassphrase); Ensure.Contains(header, "p2c", "Pbse2HmacShaWithAesKWKeyManagement algorithm expects 'p2c' param in JWT header, but was not found"); Ensure.Contains(header, "p2s", "Pbse2HmacShaWithAesKWKeyManagement algorithm expects 'p2s' param in JWT header, but was not found"); byte[] algId = Encoding.UTF8.GetBytes(header["alg"].GetString()); int iterationCount = (int)header["p2c"].GetNumber(); byte[] saltInput = Base64Url.Decode(header["p2s"].GetString()); byte[] salt = Arrays.Concat(algId, Arrays.Zero, saltInput); byte[] kek = PBKDF2.DeriveKey(sharedKey, salt, iterationCount, keySizeBits, Prf); return(aesKW.Unwrap(encryptedCek, kek, cekSizeBits, header)); }
public Part[] WrapNewKey(uint cekSizeBits, object key, JsonObject header) { var sharedPassphrase = Ensure.Type <string>(key, "Pbse2HmacShaWithAesKWKeyManagement management algorithm expectes key to be string."); byte[] sharedKey = Encoding.UTF8.GetBytes(sharedPassphrase); byte[] algId = Encoding.UTF8.GetBytes(header["alg"].GetString()); const int iterationCount = 8192; var saltInput = Buffer.ToBytes(CryptographicBuffer.GenerateRandom(12)); header["p2c"] = JsonValue.CreateNumberValue(iterationCount); header["p2s"] = JsonValue.CreateStringValue(Base64Url.Encode(saltInput)); byte[] salt = Arrays.Concat(algId, Arrays.Zero, saltInput); byte[] kek = PBKDF2.DeriveKey(sharedKey, salt, iterationCount, keySizeBits, Prf); return(aesKW.WrapNewKey(cekSizeBits, kek, header)); }
private bool ValidPass(string email, string password) { var crypt = new PBKDF2(); bool isValid = false; using (var db = new login_simpleEntities()) { var user = db.log_in.FirstOrDefault(u => u.email == email); string deCryptPass = crypt.Compute(password, user.passsalt); bool validation = user.pass == deCryptPass; if (user != null) { if (validation) { isValid = true; } } } return(isValid); }
public (string, string) ChangePassword(string oldpassword, string newpassword, string confirmnewpassword) { if (!PBKDF2.Verify(Password, oldpassword)) { return("PasswordChangeFailed", "Old password entered is incorrect."); } if (oldpassword == newpassword) { return("PasswordChangeFailed", "Old password and new password cannot be same."); } if (newpassword != confirmnewpassword) { return("PasswordChangeFailed", "New password and confirmed new password do not match"); } Password = PBKDF2.Hash(newpassword); ModifyDate = DateTime.UtcNow; return("PasswordChangeSuccess", "Password changed successfully."); }
public async Task <string> Update(string id, [FromForm] string name, [FromForm] string json, [FromForm] string password) { var quiz = await new Database().QuizCollection .FindAsync <Quiz>(x => x.Id == new ObjectId(id)).Result .SingleAsync(); if (PBKDF2.Validate(password, quiz.Password)) { var update = Builders <Quiz> .Update.Set("name", name) .Set("json", json); await new Database().QuizCollection.UpdateOneAsync( Builders <Quiz> .Filter.Eq("_id", new ObjectId(id)), update); return(id); } else { return("[Error] Invalid Password"); } }
/// <summary> /// Check if the password is valid /// </summary> /// <param name="username">Username</param> /// <param name="password">Password</param> /// <returns>If password matches</returns> public bool IsPasswordValid(string username, string password) { var user = _userFactory.CreateNewUser(username, password); Validate(user); var foundUser = _userRepository.GetBy(x => x.UserName == user.UserName); if (foundUser == null) { return(false); } var cryptoService = new PBKDF2(); string hashedPassword = cryptoService.Compute(password, foundUser.Salt); bool isPasswordValid = cryptoService.Compare(foundUser.Password, hashedPassword); return(isPasswordValid); }
public BitChatNetwork(string networkName, string sharedSecret, BinaryID networkID, Certificate[] knownPeerCerts, IBitChatNetworkManager networkManager, ISecureChannelSecurityManager securityManager) { _type = BitChatNetworkType.GroupChat; _networkName = networkName; _sharedSecret = sharedSecret; _networkManager = networkManager; _securityManager = securityManager; LoadPeers(knownPeerCerts); if (networkID == null) { //compute network id _networkID = new BinaryID(PBKDF2.CreateHMACSHA1(_sharedSecret, Encoding.UTF8.GetBytes(_networkName.ToLower()), 200000).GetBytes(20)); } else { _networkID = networkID; } }
public async Task <IActionResult> Login(string UserID, string password) { var login = await _context.Logins.Include(x => x.Customer). FirstOrDefaultAsync(x => x.UserID == UserID); if (login.Block) { ModelState.AddModelError("LoginFailed", "Your account has been locked."); HttpContext.Session.SetInt32("Block", 0); return(View(new Login { UserID = UserID })); } if (login == null || !PBKDF2.Verify(login.PasswordHash, password)) { HttpContext.Session.SetInt32("Block", HttpContext.Session.GetInt32("Block").Value + 1); ModelState.AddModelError("LoginFailed", String.Format("Login failed, please try again. left attempt: {0}", 3 - HttpContext.Session.GetInt32("Block").Value)); if (HttpContext.Session.GetInt32("Block").Value == 3) { login.Block = true; login.ModifyDate = DateTime.UtcNow; _context.Add(login); _context.Update(login); await _context.SaveChangesAsync(); } return(View(new Login { UserID = UserID })); } // Login customer. HttpContext.Session.SetInt32(nameof(Customer.CustomerID), login.CustomerID); HttpContext.Session.SetString(nameof(Customer.CustomerName), login.Customer.CustomerName); HttpContext.Session.SetString(nameof(Model.Login.UserID), UserID); return(RedirectToAction("Index", "ATM")); }
public JsonResult GuardarUsuarioLogin(List <Usuarios> dataToProcess) { Usuarios Usuario = new Usuarios(); foreach (var item in dataToProcess) { Usuario.Cod_Usuario = item.Cod_Usuario; Usuario.Nombre = item.Nombre; Usuario.Apellido = item.Apellido; Usuario.Rut = item.Rut; Usuario.Cod_Perfil = item.Cod_Perfil; Usuario.Password = item.Password; Usuario.Salt = item.Salt; Usuario.User_Log = item.User_Log; ICryptoService cryptoService = new PBKDF2(); Salt = cryptoService.GenerateSalt(); PasswordEncriptada = cryptoService.Compute(Usuario.Password); //LLENADO DE BD string constr = conexion; using (MySqlConnection con = new MySqlConnection(constr)) { con.Open(); MySqlCommand cmd = new MySqlCommand(bd + "web_pingresa_usuarios_login", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("p_Cod_Usuario", Usuario.Cod_Usuario); cmd.Parameters.AddWithValue("p_Nombre", Usuario.Nombre); cmd.Parameters.AddWithValue("p_Apellido", Usuario.Apellido); cmd.Parameters.AddWithValue("p_Rut", Usuario.Rut); cmd.Parameters.AddWithValue("p_Cod_Perfil", Usuario.Cod_Perfil); cmd.Parameters.AddWithValue("p_Password", PasswordEncriptada); cmd.Parameters.AddWithValue("p_salt", Salt); cmd.Parameters.AddWithValue("p_User_Log", Usuario.User_Log); cmd.Parameters.AddWithValue("p_Password_Dsk", Usuario.Password); cmd.ExecuteNonQuery(); con.Close(); } } return(Json(dataToProcess, JsonRequestBehavior.AllowGet)); }
/// <summary> /// Encrypts a stream using a key derived from the passphrase. /// </summary> /// <param name="inputStream">The stream to encrypt.</param> /// <param name="outputStream">The encrypted stream.</param> /// <param name="passphrase">The passphrase from which the encryption key is derived.</param> public override void EncryptStream(Stream inputStream, Stream outputStream, string passphrase) { if (inputStream == null || outputStream == null) { throw new ArgumentNullException(); } byte[] salt; byte[] key = PBKDF2.ComputeHash(passphrase, out salt, saltNumBytes: SALT_SIZE_BYTES, passwordNumBytes: KEY_SIZE_BYTES); byte[] iv = null; int ivLength = GetIVSizeBytes(); if (ivLength != 0) { iv = SecureRandomizer.GetRandomBytes(ivLength); outputStream.Write(iv, 0, iv.Length); } outputStream.Write(salt, 0, salt.Length); using (var algo = new AesCryptoServiceProvider()) { algo.Mode = GetCipherMode(); using (var encryptor = algo.CreateEncryptor(key, iv)) { using (var cryptoStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write)) { using (var binaryWriter = new BinaryWriter(cryptoStream)) { var buffer = new byte[Defaults.BUFFER_SIZE]; int count; while ((count = inputStream.Read(buffer, 0, buffer.Length)) > 0) { binaryWriter.Write(buffer, 0, count); } } } } } }
public bool SalvaRegistrazione(ControllerContext controller, DatabaseContext db) { CONTO_CORRENTE conto = db.CONTO_CORRENTE.Create(); conto.ID = Guid.NewGuid(); conto.TOKEN = Guid.NewGuid(); conto.DATA_INSERIMENTO = DateTime.Now; conto.STATO = (int)Stato.ATTIVO; db.CONTO_CORRENTE.Add(conto); db.SaveChanges(); PBKDF2 crypto = new PBKDF2(); PERSONA persona = db.PERSONA.Create(); persona.TOKEN = Guid.NewGuid(); persona.TOKEN_PASSWORD = crypto.GenerateSalt(1, 20); persona.PASSWORD = crypto.Compute(this.Password.Trim(), persona.TOKEN_PASSWORD); //persona.NOME = this.Nome.Trim(); //persona.COGNOME = this.Cognome.Trim(); persona.ID_CONTO_CORRENTE = conto.ID; persona.ID_ABBONAMENTO = db.ABBONAMENTO.SingleOrDefault(item => item.NOME == "BASE").ID; persona.DATA_INSERIMENTO = DateTime.Now; persona.STATO = (int)Stato.INATTIVO; db.PERSONA.Add(persona); if (db.SaveChanges() > 0) { PERSONA_EMAIL personaEmail = db.PERSONA_EMAIL.Create(); personaEmail.ID_PERSONA = persona.ID; personaEmail.EMAIL = this.Email.Trim(); personaEmail.TIPO = (int)TipoEmail.Registrazione; personaEmail.DATA_INSERIMENTO = DateTime.Now; personaEmail.STATO = (int)Stato.INATTIVO; db.PERSONA_EMAIL.Add(personaEmail); if (db.SaveChanges() > 0) { InvioEmail(controller, persona, personaEmail); return(true); } } return(false); }
/// <summary> /// Decrypts a stream using a given key. /// </summary> /// <param name="inputStream">The encrypted stream.</param> /// <param name="outputStream">The decrypted stream.</param> /// <param name="passphrase">The passphrase from which the encryption key is derived.</param> public override void DecryptStream(Stream inputStream, Stream outputStream, string passphrase) { if (inputStream == null) { return; } byte[] iv = null; int ivLength = GetIVSizeBytes(); if (ivLength != 0) { iv = new byte[ivLength]; inputStream.Read(iv, 0, iv.Length); } byte[] salt = new byte[SALT_SIZE_BYTES]; inputStream.Read(salt, 0, salt.Length); byte[] key = PBKDF2.ComputeHash(passphrase, salt, passwordNumBytes: KEY_SIZE_BYTES); using (var algo = new AesCryptoServiceProvider()) { algo.Mode = GetCipherMode(); using (var decryptor = algo.CreateDecryptor(key, iv)) { using (var decryptorStream = new CryptoStream(outputStream, decryptor, CryptoStreamMode.Write)) { using (var binaryWriter = new BinaryWriter(decryptorStream)) { var buffer = new byte[Defaults.BUFFER_SIZE]; int count; while ((count = inputStream.Read(buffer, 0, buffer.Length)) > 0) { binaryWriter.Write(buffer, 0, count); } } } } } }
private void Initialize() { var utf8 = new UTF8Encoding(false); var paramz = new PBKDF2(utf8.GetBytes(password), salt, RFC2898_ITERATIONS); KeyBytes = paramz.GetBytes(KeySizeInBytes); IvBytes = paramz.GetBytes(KeySizeInBytes); generatedVerifyValue = paramz.GetBytes(2); short verify = BitConverter.ToInt16(passwordVerifyValue, 0); if (password != null) { short generated = BitConverter.ToInt16(generatedVerifyValue, 0); if (verify != generated) { throw new InvalidFormatException("bad password"); } } }
public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { var crypto = new PBKDF2(); var user = userService.GetUsers().FirstOrDefault(u => u.UserName == User.Identity.Name); if (user.Password == crypto.Compute(model.OldPassword, user.PasswordSalt)) { user.Password = crypto.Compute(model.NewPassword); user.ConfirmPassword = crypto.Compute(model.ConfirmPassword); userService.UpdateUser(user); return(RedirectToAction("ChangePasswordSuccess")); } ModelState.AddModelError("", "The current password is incorrect or the new password is invalid."); } return(View(model)); }
public string ChangePassword(string strpass, string strnewpass, string memberid, string email) { MembersTableAdapters.MembersTableAdapter taMember = new MembersTableAdapters.MembersTableAdapter(); if (taMember.GetDataByMemberID(memberid).Count > 0) { DataRow dtMember = taMember.GetDataByMemberID(memberid).Rows[0]; ValidateLogin valLogin = new ValidateLogin(); if (valLogin.isValid(email, strpass)) { ICryptoService cryptoService = new PBKDF2(); //save this salt to the database string PasswordSalt = cryptoService.GenerateSalt(); //save this hash to the database string hashedPassword = cryptoService.Compute(strnewpass); taMember.UpdatePassword(hashedPassword, PasswordSalt, DateTime.Now, Convert.ToInt32(dtMember["AutoID"])); return "valid"; } else { return "invalid"; } } taMember.Dispose(); return "invalid"; }
public static void SetNewPassword(User user, string newPassword) { ICryptoService cryptoService = new PBKDF2(); int SALT_SIZE = 16; int HASH_ITERATIONS = 20; PasswordHash.CreateHash(user,newPassword); //a new password hash is generated from a generated salt with the passed settings // user.Password = cryptoService.Compute(newPassword, SALT_SIZE, HASH_ITERATIONS); //assigning the generated salt to the user //user.PasswordSalt = cryptoService.Salt; }
/// <summary> /// Return a Base64 encoded PBKDF2 password string. /// </summary> /// <param name="password">The plaintext password string.</param> /// <param name="salt">The salt string.</param> /// <returns></returns> public static string GeneratePassword(string password, string salt) { var input = password.Trim(); var pbk = new PBKDF2(input, salt); var raw = pbk.GetBytes(256); var txt = System.Text.Encoding.Default.GetString(raw); var pwd = Convert.ToBase64String(raw); return pwd; }
/// <summary> /// /// </summary> /// <param name="password"></param> /// <param name="algorithm"></param> /// <param name="salt">De te gebruiken salt, welke minimaal uit 16 karakters dient te bestaan</param> /// <param name="key">De primaire (master) sleutel waarmee de hash gegenereerd dient te worden</param> /// <returns></returns> public static PasswordResult HashPassword(string password, EnmSecureHashingAlgorithm algorithm, string salt, string key) { // Controleer parameters if (String.IsNullOrEmpty(password)) throw new ArgumentNullException("password"); if (salt == null || salt.Length < SALT_LENGTH) throw new ArgumentException("Must be atleast " + SALT_LENGTH.ToString() + " characters in length", "salt"); if (key == null || key.Length < MIN_SECRETKEY_LENGTH) throw new ArgumentException("Must be atleast " + MIN_SECRETKEY_LENGTH.ToString() + " characters in length", "masterKey"); // Genereer een salt en converteer het wachtwoord naar bytes var factory = HMACFactories.HMACSHA512; var saltBytes = Encoding.ASCII.GetBytes(salt); var passwordBytes = Encoding.ASCII.GetBytes(password); var generatedHash = new PBKDF2(factory, passwordBytes, saltBytes, HASH_ITERATIONS).GetBytes(64); return new PasswordResult(algorithm.ToString(), HASH_ITERATIONS, Convert.ToBase64String(saltBytes), Convert.ToBase64String(generatedHash)); }
internal virtual ICryptoService CreateICryptoService() { ICryptoService target = new PBKDF2(); return target; }
/// <summary> /// Implements a <see cref="PBKDF2"/> algorthim with a user definded MAC method. /// </summary> /// <param name="method">the HMAC method to use.</param> /// <param name="password">the password to use</param> /// <param name="salt">the salt. Must be at least 64-bit</param> /// <param name="iterations">the number of iterations. Must be at least 1000</param> /// <param name="length">the number of bytes to return</param> /// <returns> /// A salted password based on the specified length. /// </returns> public static byte[] ComputeSaltedPassword(HMACMethod method, byte[] password, byte[] salt, int iterations, int length) { using (var kdf = new PBKDF2(method, password, salt, iterations)) { return kdf.GetBytes(length); } }
public virtual bool Match(string password) { var cryptoService = new PBKDF2(); return String.CompareOrdinal(cryptoService.Compute(password, Salt), EncryptedPassword) == 0; }
internal static byte[] GenerateSaltedPassword(byte[] passwordBytes, byte[] salt, int iterations) { using (var pass = new PBKDF2(HMACMethod.SHA512, passwordBytes, salt, iterations)) { return pass.GetBytes(PasswordSize); } }
/// <summary> /// Valideer of een wachtwoord geldig is door deze met de beveiligde hash te vergelijken. /// </summary> /// <param name="password">Het te valideren wachtwoord</param> /// <param name="passwordHash">De secure string (gegenereerd met de methode HashPassword)</param> /// <returns>True indien het wachtwoord overeen komt met de secure hash</returns> public static bool ValidatePasswordHash(string password, string passwordHash) { if (String.IsNullOrEmpty(password)) throw new ArgumentException("password"); if (String.IsNullOrEmpty(passwordHash)) throw new ArgumentException("passwordHash"); var data = new PasswordResult(passwordHash); // Bereid de parameters voor op gebruik var passwordBytes = Encoding.ASCII.GetBytes(password); // Het te valideren wachtwoor als bytes var saltBytes = Convert.FromBase64String(data.Salt); // Het te valideren wachtwoor als bytes var generatedHash = new PBKDF2(data.Factory, passwordBytes, saltBytes, data.Iterations).GetBytes(64); var hashedBytes = Convert.FromBase64String(data.Hash); return SlowEquals(generatedHash, hashedBytes); }
/// <summary> /// Valideer of een wachtwoord geldig is door deze met de ingevoerde parameters te vergelijken. /// </summary> /// <param name="password">Het plain text wachtwoodr dat vergeleken moet worden met de secure hash</param> /// <param name="method">Het te gebruiken hashing algorithme</param> /// <param name="salt">Base-64 Encoded salt (gegenereerd met de methode HashPassword)</param> /// <param name="iteraties">Het aantal hashing iteraties</param> /// <param name="passwordHash">Base-64 Encoded password hash(Zoals gegenereerd uit de methode HashPassword)</param> /// <returns>True indien het wachtwoord overeen komt met de secure hash</returns> public static bool ValidatePasswordHash(string password, EnmSecureHashingAlgorithm method, string salt, int iteraties, string passwordHash) { // Valideer input if (String.IsNullOrEmpty(password)) throw new ArgumentNullException("password"); if (iteraties < 1) throw new ArgumentNullException("Value must be greater then 0", "iteraties"); if (String.IsNullOrEmpty(salt)) throw new ArgumentNullException("salt"); if (String.IsNullOrEmpty(passwordHash)) throw new ArgumentNullException("passwordHash"); // Bereid de parameters voor op gebruik var factory = method.Factory(); // De te gebruiken HMACSHA algoritme var passwordBytes = Convert.FromBase64String(password); // Het te valideren wachtwoor als bytes var saltBytes = Convert.FromBase64String(salt); // Het te valideren wachtwoor als bytes var generatedHash = new PBKDF2(factory, passwordBytes, saltBytes, iteraties).GetBytes(64); // Slow compare return SlowEquals(generatedHash, Convert.FromBase64String(passwordHash)); }
/// <summary> /// Genereer een veilige(re) hash voor een string die belangrijke data bevat, zoals een wachtwoord. /// Deze methode is CPU intensiever dan de methode 'HashString', welke op zijn beurt beter gebruikt kan worden voor snelle en simpele authenticatie hashes. /// </summary> /// <param name="password">De veilige string welke gehashed moet worden</param> /// <returns>De gehashde string welke in zijn volledigheid opgeslagen dient te worden, in het formaat: ALGORITME:ITERATIES:SALT:HASH</returns> public static string HashPassword(string password) { // Controleer parameters if (String.IsNullOrEmpty(password)) throw new ArgumentNullException("password"); var passwordBytes = Encoding.ASCII.GetBytes(password); var saltBytes = GenerateSalt(); var generatedHash = new PBKDF2(EnmSecureHashingAlgorithm.HMACSHA512.Factory(), passwordBytes, saltBytes, HASH_ITERATIONS).GetBytes(64); return new PasswordResult(EnmSecureHashingAlgorithm.HMACSHA512.ToString(), HASH_ITERATIONS, Convert.ToBase64String(saltBytes), // Base-64 salt Convert.ToBase64String(generatedHash)) // Base-64 hash .ToString(); // Retourneer de secure string. Het object gaan we niet teruggeven }
public static string GetPasswordHash(string password) { ICryptoService cryptoService = new PBKDF2(); int SALT_SIZE = 16; int HASH_ITERATIONS = 20; return cryptoService.Compute(password, SALT_SIZE, HASH_ITERATIONS); }
void TestSHA512(string P, string S, int c, int dkLen, string dk) { byte[] dkExpected = StringToByteArray(dk); using (var pdf = new PBKDF2(HMACMethod.SHA512, Encoding.ASCII.GetBytes(P), Encoding.ASCII.GetBytes(S), c)) { byte[] dkBytes = pdf.GetBytes(dkLen); if (!dkBytes.SequenceEqual(dkExpected)) { throw new Exception(); } } }