public bool VerifyPassword(string hash, string password) { var parts = hash.Split('.', 2); if (parts.Length != 2) { return(false); } var salt = Convert.FromBase64String(parts[0]); var passwordHash = parts[1]; string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: password, salt: salt, prf: KeyDerivationPrf.HMACSHA512, iterationCount: 10000, numBytesRequested: 256 / 8)); return(passwordHash == hashed); }
/// <summary> /// Verifies by hashing the value and matching it with the provided hash. /// Returns true if the hashes match and false otherwise. /// </summary> /// <param name="value">Value to compare with hash</param> /// <param name="hash">Hash to compare value with</param> /// <returns>True if the hash values are equal and false otherwise</returns> public static bool Verify(string value, string hash) { var hashBytes = Convert.FromBase64String(hash); if (hashBytes.Length != 1 + SaltSize + SubkeyLength) { return(false); } var salt = new byte[SaltSize]; Buffer.BlockCopy(hashBytes, 1, salt, 0, salt.Length); var subkey = new byte[SubkeyLength]; Buffer.BlockCopy(hashBytes, 1 + salt.Length, subkey, 0, subkey.Length); var valueSubkey = KeyDerivation.Pbkdf2(value, salt, Pbkdf2Prf, IterCount, SubkeyLength); return(CryptographicOperations.FixedTimeEquals(subkey, valueSubkey)); }
public void Post([FromBody] UserSchema RegData) { string password = RegData.Password; // generate a 128-bit salt using a secure PRNG byte[] salt = new byte[128 / 8]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(salt); } Console.WriteLine($"Salt: {Convert.ToBase64String(salt)}"); // derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations) string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: password, salt: salt, prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8)); var data = RegData; }
public static string Hash(string password, string salt) { String[] tempAry = salt.Split('-'); byte[] decBytes = new byte[tempAry.Length]; for (int i = 0; i < tempAry.Length; i++) { decBytes[i] = Convert.ToByte(tempAry[i], 16); } // derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations) string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: password, salt: decBytes, prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8)); return(hashed); }
public static byte[] HashPassword(string password) { var salt = new byte[_saltSize]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(salt); } byte[] subkey = KeyDerivation.Pbkdf2(password, salt, _prf, _iterCount, _keyBytes); var outputBytes = new byte[13 + salt.Length + subkey.Length]; outputBytes[0] = 0x01; // format marker WriteNetworkByteOrder(outputBytes, 1, (uint)_prf); WriteNetworkByteOrder(outputBytes, 5, (uint)_iterCount); WriteNetworkByteOrder(outputBytes, 9, (uint)_saltSize); Buffer.BlockCopy(salt, 0, outputBytes, 13, salt.Length); Buffer.BlockCopy(subkey, 0, outputBytes, 13 + _saltSize, subkey.Length); return(outputBytes); }
private Tuple <string, string> HashPassword(string passwordString) { // generate a 128-bit salt using a secure PRNG byte[] saltBytes = new byte[128 / 8]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(saltBytes); } var passwordSecret = Convert.ToBase64String(saltBytes); // derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations) string passwordHash = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: passwordString, salt: saltBytes, prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8)); return(new Tuple <string, string>(passwordSecret, passwordHash)); }
static void Main(string[] args) { int? v = null; MarkEnum?m; m = (MarkEnum?)v; if (Enum.IsDefined(typeof(MarkEnum), v)) { } else { Console.Write("Not in range"); } //SeedData.Seed(); //Console.Write(Guid.NewGuid().ToString()); Console.ReadLine(); return; Console.Write("Enter a password: "******"Salt: {Convert.ToBase64String(salt)}"); // derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations) string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: password, salt: salt, prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8)); Console.WriteLine($"Hashed: {hashed}"); Console.ReadLine(); }
public PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string password) { if (password == null) { throw new ArgumentNullException(nameof(password)); } if (hashedPassword == null) { return(PasswordVerificationResult.Failed); } byte[] numArray = Convert.FromBase64String(hashedPassword); if (numArray.Length < 1) { return(PasswordVerificationResult.Failed); } byte[] salt = new byte[SaltSize]; Buffer.BlockCopy(numArray, 0, salt, 0, SaltSize); byte[] storedHashedPassword = new byte[SubkeyLength]; Buffer.BlockCopy(numArray, 0 + SaltSize, storedHashedPassword, 0, SubkeyLength); var newHashedPassword = KeyDerivation.Pbkdf2( password: password, salt: salt, prf: KeyDerivationPrf.HMACSHA256, iterationCount: IterationCount, numBytesRequested: SubkeyLength ); if (CryptographicOperations.FixedTimeEquals(storedHashedPassword, newHashedPassword)) { return(PasswordVerificationResult.Success); } return(PasswordVerificationResult.Failed); }
public async Task <IActionResult> Login(LoginView loginView) { try { string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: loginView.Clave, salt: System.Text.Encoding.ASCII.GetBytes("Salt"), prf: KeyDerivationPrf.HMACSHA1, iterationCount: 1000, numBytesRequested: 256 / 8)); var p = contexto.Usuarios.FirstOrDefault(x => x.Email == loginView.Usuario); if (p == null || p.Clave != hashed) { return(BadRequest("Nombre de usuario o clave incorrecta")); } else { var key = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(config["TokenAuthentication:SecretKey"])); var credenciales = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var claims = new List <Claim> { new Claim(ClaimTypes.Name, p.Email), new Claim(ClaimTypes.Role, "Propietario"), }; var token = new JwtSecurityToken( issuer: config["TokenAuthentication:Issuer"], audience: config["TokenAuthentication:Audience"], claims: claims, expires: DateTime.Now.AddMinutes(60), signingCredentials: credenciales ); return(Ok(new JwtSecurityTokenHandler().WriteToken(token))); } } catch (Exception ex) { return(BadRequest(ex)); } }
public async Task<IActionResult> Iniciar(string email, string clave) { try { Usuario usuario = repositorioUsuario.ObtenerPorEmail(email); string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: clave, salt: System.Text.Encoding.ASCII.GetBytes(configuration["Salt"]), prf: KeyDerivationPrf.HMACSHA1, iterationCount: 1000, numBytesRequested: 256 / 8)); if (usuario == null || usuario.Clave != hashed) { return View(); } var claims = new List<Claim> { new Claim(ClaimTypes.Name, usuario.Email), new Claim("FullName", usuario.Nombre + " " + usuario.Apellido), new Claim(ClaimTypes.Role, usuario.RolNombre), }; ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)); TempData["Info"] = "Inicio de sesión correcto."; return RedirectToAction("Index", "Home"); } catch (Exception ex) { TempData["Error"] = "Error de inicio de sesion"; return View(); } }
public async Task <LoginResponse> Login([FromBody] LoginRequest request) { if (request.UserId <= 0 || string.IsNullOrEmpty(request.Password)) { Response.StatusCode = 400; return(new LoginResponse { StatusCode = 400, Message = "Invalid user id or password." }); } var passwordHash = Convert.ToBase64String(KeyDerivation.Pbkdf2(request.Password, Encoding.ASCII.GetBytes(jwtOptions.Value.SigningKey), KeyDerivationPrf.HMACSHA256, 1000, 256 / 8)); var us = await userSecurityRepository.GetEntityByIdAsync(request.UserId); if (us == null || us.PasswordHash != passwordHash) { Response.StatusCode = 400; return(new LoginResponse { StatusCode = 400, Message = "Invalid user id or password." }); } var u = await userRepository.GetEntityByIdAsync(request.UserId); return(new LoginResponse { Content = new() { EmailAddress = u.EmailAddress, Id = u.Id, IsFollowed = false, UserName = u.UserName, UserRole = new() { Id = u.UserRole.Id, AccessLevel = u.UserRole.AccessLevel, Name = u.UserRole.Name }, }, StatusCode = 200, Message = "OK", Token = GetJwtToken(u) });
public IActionResult ChkPw(ChkPwViewModel model) { if (HttpContext.Session.GetInt32("USER_LOGIN_KEY") == null) { return(RedirectToAction("Login", "Account")); } // 현재 로그인 중인 유저의 No값 가져오기 var id = int.Parse(HttpContext.Session.GetInt32("USER_LOGIN_KEY").ToString()); if (id == 0) { return(NotFound()); } if (ModelState.IsValid) { using (var db = new BoardDbContext()) { // 가져온 유저의 No값으로 DB에서 해당하는 유저 객체를 가져온다 var user = db.Users.Find(id); var pw = user.UserPw; // DB에 저장되어있는 Password string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: model.UserPw, // 사용자가 입력한 Password salt: user.UserSalt, prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8 )); // 생성된 해시값이랑 DB에 저장되어있는 해시값이 같으면 if (pw.Equals(hashed)) { return(RedirectToAction("ChangeInfo", "Account")); } } ModelState.AddModelError(string.Empty, "비밀번호를 잘못 입력하셨습니다."); } return(View()); }
/// <summary> /// Encrypt the legacy password using the DJango approach /// </summary> /// <remarks> /// Reference: https://docs.djangoproject.com/en/3.1/topics/auth/passwords/ /// By default, Django uses the PBKDF2 algorithm with a SHA256 hash /// The DB stores the password in this format: <algorithm>$<iterations>$<salt>$<hash> /// Example: "pbkdf2_sha256$216000$r1jfzvUNnesy$HazE155XipRbEWq4JWc2YNCetEH/zYd+H8zaobU1x10=" /// </remarks> /// <param name="encoded"> /// User's password in the user table as is from the DB (encrypted). It may be in the old format (described in remarks). Or in our converted format. /// Either way, test if the password passed in matches the encrypted portion of the legacyPassword. /// </param> /// <param name="password"> /// The password. /// </param> /// <returns> /// true/false - is there a match using the legacy password conversion /// </returns> public static bool ValidateLegacyPassword(string encoded, string password) { if (string.IsNullOrEmpty(encoded)) { return(false); } if (string.IsNullOrEmpty(password)) { return(false); } string[] passwordParts = encoded.Split(_delimiterLegacy); if (passwordParts.Length < 4) { return(false); } if (passwordParts[0] != "pbkdf2_sha256") { throw new NotSupportedException($"Password - invalid legacy encryption format: {passwordParts[0]}."); } //by inspecting Django code //force salt to bytes int numBytes = 32; var salt = passwordParts[2]; var convertedSalt = System.Text.Encoding.UTF8.GetBytes(salt); //perform hash var hash = KeyDerivation.Pbkdf2( password: password, salt: convertedSalt, prf: KeyDerivationPrf.HMACSHA256, iterationCount: Convert.ToInt32(passwordParts[1]), numBytesRequested: numBytes); var hashed = Convert.ToBase64String(hash); //true if they match return(hashed == passwordParts[3]); }
public ActionResult CambiarPass(int id, CambioClaveView cambio) { Usuario usuario = null; try { usuario = repositorioUsuario.ObtenerPorId(id); if (ModelState.IsValid) { usuario.Clave = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: cambio.ClaveNueva, salt: System.Text.Encoding.ASCII.GetBytes("Salt"), prf: KeyDerivationPrf.HMACSHA1, iterationCount: 1000, numBytesRequested: 256 / 8)); repositorioUsuario.Modificacion(usuario); TempData["Mensaje"] = "Contraseña actualizada correctamente. Ingresar nuevamente por favor"; return(RedirectToAction("Logout")); } else { foreach (ModelStateEntry modelState in ViewData.ModelState.Values) { foreach (ModelError error in modelState.Errors) { TempData["Error"] += error.ErrorMessage + "\n"; } } return(RedirectToAction("Edit", new { id = id })); } } catch (Exception ex) { TempData["Error"] = ex.Message; TempData["StackTrace"] = ex.StackTrace; return(RedirectToAction("Edit", new { id = id })); } }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "user/{id}")] HttpRequest req, [CosmosDB( databaseName: "db", collectionName: "coll", ConnectionStringSetting = "CosmosDBConnection", PartitionKey = "{id}", Id = "{id}")] dynamic user, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); bool authSuccess = false; string token = String.Empty; log.LogInformation($"{user.ToString()}"); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: data.password.ToString(), salt: Convert.FromBase64String(user.salt), prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8)); log.LogInformation($"Computed: {hashed}"); log.LogInformation($"Stored: {hashed}"); if (hashed == user.hash) { authSuccess = true; token = Token.CreateToken(secret, user.id); } return(authSuccess == true ? (ActionResult) new OkObjectResult(token) : new BadRequestObjectResult("Please pass a name on the query string or in the request body")); }
public int CheckCred(LoginRequestcs request) { using (var con = new SqlConnection("Data Source=db-mssql;Initial Catalog=s18663;Integrated Security=True")) using (var com = new SqlCommand()) { con.Open(); com.Connection = con; com.CommandText = "select Salt from Student where IndexNumber=@index"; com.Parameters.AddWithValue("index", request.login); var dr = com.ExecuteReader(); dr.Read(); var salt = dr["Salt"].ToString(); dr.Close(); var valueBytes = KeyDerivation.Pbkdf2( password: request.pass, salt: Encoding.UTF8.GetBytes(salt), prf: KeyDerivationPrf.HMACSHA512, iterationCount: 10000, numBytesRequested: 256 / 8); string hash = Convert.ToBase64String(valueBytes); com.Connection = con; com.CommandText = "Select count(1) from Student where IndexNumber=@index and Pass=@pass"; com.Parameters.AddWithValue("index", request.login); com.Parameters.AddWithValue("pass", hash); dr = com.ExecuteReader(); int count = 0; if (dr.Read()) { count = (int)dr.GetValue(0); } dr.Close(); return(count); } }
private static bool VerifyHashedPassword(byte[] hashedPassword, string password, out int iterCount) { iterCount = default; try { // Read header information KeyDerivationPrf prf = (KeyDerivationPrf)ReadNetworkByteOrder(hashedPassword, 1); iterCount = (int)ReadNetworkByteOrder(hashedPassword, 5); int saltLength = (int)ReadNetworkByteOrder(hashedPassword, 9); // Read the salt: must be >= 128 bits if (saltLength < 128 / 8) { return(false); } byte[] salt = new byte[saltLength]; Buffer.BlockCopy(hashedPassword, 13, salt, 0, salt.Length); // Read the subkey (the rest of the payload): must be >= 128 bits int subkeyLength = hashedPassword.Length - 13 - salt.Length; if (subkeyLength < 128 / 8) { return(false); } byte[] expectedSubkey = new byte[subkeyLength]; Buffer.BlockCopy(hashedPassword, 13 + salt.Length, expectedSubkey, 0, expectedSubkey.Length); // Hash the incoming password and verify it byte[] actualSubkey = KeyDerivation.Pbkdf2(password, salt, prf, iterCount, subkeyLength); return(ByteArraysEqual(actualSubkey, expectedSubkey)); } catch { // This should never occur except in the case of a malformed payload, where // we might go off the end of the array. Regardless, a malformed payload // implies verification failed. return(false); } }
public ActionResult Create(Propietario propietario) { ViewBag.propietarios = repositorio.ObtenerTodos(); foreach (var item in (IList <Propietario>)ViewBag.propietarios) { if (item.Email == propietario.Email || item.Dni == propietario.Dni) { ViewBag.Error2 = "Error: Ya existe un propietario con ese email o dni"; return(View()); } } try { TempData["Nombre"] = propietario.Nombre; if (ModelState.IsValid) { propietario.Clave = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: propietario.Clave, salt: System.Text.Encoding.ASCII.GetBytes("SALADA"), prf: KeyDerivationPrf.HMACSHA1, iterationCount: 1000, numBytesRequested: 256 / 8)); repositorio.Alta(propietario); TempData["Alta"] = "Propietario agregado exitosamente!"; return(RedirectToAction(nameof(Index))); } else { return(View()); } } catch (Exception ex) { ViewBag.Error = ex.Message; ViewBag.StackTrate = ex.StackTrace; return(View()); } }
public UserWithTokenDto Login(UserLoginDto data) { var user = context.Users.SingleOrDefault(x => x.Username == data.Username); if (user == null) { throw new ServiceException("Invalid username or password!"); } var salt = Convert.FromBase64String(user.Salt); var hashedPassword = user.HashedPassword; string hashedIncomingPassword = Convert.ToBase64String( KeyDerivation.Pbkdf2( password: data.Password, salt: salt, prf: Algorithm, iterationCount: HashingIterationsCount, numBytesRequested: PasswordNumberOfBytes ) ); if (hashedPassword != hashedIncomingPassword) { throw new ServiceException("Invalid username or password!"); } var token = GenerateToken(user); var userWithToken = new UserWithTokenDto { Username = user.Username, FirstName = user.FirstName, LastName = user.LastName, Role = user.Role == null ? "User" : user.Role, Token = token, }; return(userWithToken); }
public static bool VerifyHashedPassword(string hashedPassword, string providedPassword) { var decodedHashedPassword = Convert.FromBase64String(hashedPassword); // Wrong version if (decodedHashedPassword[0] != 0x01) { return(false); } // Read header information var prf = (KeyDerivationPrf)ReadNetworkByteOrder(decodedHashedPassword, 1); var iterCount = (int)ReadNetworkByteOrder(decodedHashedPassword, 5); var saltLength = (int)ReadNetworkByteOrder(decodedHashedPassword, 9); // Read the salt: must be >= 128 bits if (saltLength < 128 / 8) { return(false); } var salt = new byte[saltLength]; Buffer.BlockCopy(decodedHashedPassword, 13, salt, 0, salt.Length); // Read the subkey (the rest of the payload): must be >= 128 bits var subkeyLength = decodedHashedPassword.Length - 13 - salt.Length; if (subkeyLength < 128 / 8) { return(false); } var expectedSubkey = new byte[subkeyLength]; Buffer.BlockCopy(decodedHashedPassword, 13 + salt.Length, expectedSubkey, 0, expectedSubkey.Length); // Hash the incoming password and verify it var actualSubkey = KeyDerivation.Pbkdf2(providedPassword, salt, prf, iterCount, subkeyLength); return(actualSubkey.SequenceEqual(expectedSubkey)); }
static void Main(string[] args) { var listeNAS = new[] { "123123123", "123123123", "123456789", "987654321" }; var listeSalt = new[] { "9ea06ad1e0b98873ad9187da93fa4256", "0aa224cdd95bc746c240044af429eb4e", "62b9e822e8001e92e7869fac9accd7b0", "b45b19e3f9b44fbea4b7b7d38dc1ec3e", "86cb72ddc049b04ce6cb7d58c7be9a37", "12400ed6b95e573d01e376c3b60434ef", "17f4d2bc43aeee4a37091704224de2a0", "cfec6f37a2e4f6679531e7b44735af07", "ba3b69eb11b156927faede6c6f5b6d1d", "6b6231242838b2110aa82ed4876c3486", "3d3abeb0fcb16bf7b868248715a17630", "59507d0b7c969c5cb742e00c749e5ad1", "3c669aa29f58aa37d239f5519fd7517c", "7266e2166f3eabf9c8deb24ee1d4ede2", "d6963586d80581e11a6591d73aab2969", "da4c7da1ab5b6f8a08ab0ae0596006ee" }; foreach (var i in listeNAS) { //Convertir le nas en hex var nas = Int32.Parse(i); var hex = nas.ToString("X2"); var pos = Int32.Parse(hex[0].ToString(), System.Globalization.NumberStyles.HexNumber); //Choisir un des 16 salt var salt = Encoding.UTF8.GetBytes(listeSalt[pos - 1]); var result = KeyDerivation.Pbkdf2(hex, salt, KeyDerivationPrf.HMACSHA256, 10001, 60); Console.WriteLine(Convert.ToBase64String(result)); } Console.ReadLine(); }
public async Task <ActionResult <SecureToken> > LoginUser(User user) { _logger.LogInformation("Reached Login Point"); var pw = user.PasswordHash; if (!UsernameExists(user.Username)) { return(StatusCode(303)); } var logging_in_user = await _context.Users.Where(e => e.Username == user.Username).FirstAsync(); var salt = logging_in_user.Salt; string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: pw, salt: salt, prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8)); if (hashed != logging_in_user.PasswordHash) { return(Unauthorized()); } // need to create a new id token and put it in the DB. Then return it. SecureToken token_new = new SecureToken(logging_in_user.Id); try { logging_in_user.LastAuthed = token_new.LastAuthed; logging_in_user.IdToken = token_new.IdToken; logging_in_user.TokenExpiresIn = token_new.ExpiresIn; await _context.SaveChangesAsync(); } catch (DbUpdateException) { ModelState.AddModelError("", "Could not update user when logging in"); return(StatusCode(StatusCodes.Status500InternalServerError)); } return(CreatedAtAction("GetUser", "Users", new { id = logging_in_user.Id }, token_new)); }
/// <summary> /// Check that a given hash matches the input string /// </summary> /// <param name="hash">The hash to use to check</param> /// <param name="input">The string to check</param> /// <returns>If it matches</returns> public bool CheckMatch(string hash, String input) { try { // Pull apart the hash to seperate the salt and the hash parts var parts = hash.Split(':'); // Get the salt var salt = Convert.FromBase64String(parts[0]); // use the key derivation algorithm with the salt (vector) to re-run the hash var bytes = KeyDerivation.Pbkdf2(input.ToString(), salt, KeyDerivationPrf.HMACSHA512, 10000, 16); // Check equality of the resulting hash to see if they match return(parts[1].Equals(Convert.ToBase64String(bytes))); } catch { // Failed to work, so failed in general return(false); } }
public void OnPost() { // String to be hashed string password = "******"; // Generate a 128-bit salt using a secure PRNG byte[] salt = new byte[128 / 8]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(salt); } // Derive a 256-bit subkey (Use HMACSHA1 with 10,000 iterations) @ViewData["generatedPassword"] = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: password, salt: salt, prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8 )); Console.WriteLine($"Generated password: {@ViewData["generatedPassword"]}"); }
public static string GetDerivationKeyHash(this string target, byte[] salt = null) { if (salt is null) { salt = new byte[128 / 8]; using var random = RandomNumberGenerator.Create(); random.GetBytes(salt); } return(Convert.ToBase64String ( KeyDerivation.Pbkdf2 ( password: target, salt: salt, prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8 ) )); }
[HttpPost]//login user public async Task <ActionResult <IEnumerable <mData> > > PostData(mData data) { var connection = _context.Database.GetDbConnection(); byte[] salt = new byte[128 / 8]; string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: data.userPass, salt: salt, prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8) ); //check if user is in database var checkdb = await connection.QueryAsync <mData>("SELECT * FROM loginUser WHERE userName = @namecheck AND userPass = @passcheck", new { namecheck = data.userName, passcheck = hashed }); Console.WriteLine(checkdb); if (checkdb.Any())//checks if exists in db .any asks if elements are in inside checkdb { var arr = checkdb.ToArray(); var checkRole = await connection.QueryAsync <mData>("SELECT * FROM userRole WHERE id = @_id", new { _id = arr[0].id }); return(checkRole.ToList()); } else//create user and configure database around their information { string sqlInsert = "INSERT INTO loginUser (userName, userPass) Values (@uName, @uPass );"; sqlInsert += "INSERT INTO userRole (adminRole, helpDesk, userCred) Values (@aRole, @hDesk, @uCred);"; sqlInsert += "INSERT INTO user(loginID, roleID)VALUEs(LAST_INSERT_ID(), LAST_INSERT_ID());"; sqlInsert += "INSERT INTO history (userID) VALUES(LAST_INSERT_ID());"; var affectedRows = await connection.ExecuteAsync(sqlInsert, new { uName = data.userName, uPass = hashed, aRole = data.adminRole, hDesk = data.helpDesk, uCred = data.userCred }); var newUser = await connection.QueryAsync <mData>("SELECT * FROM user RIGHT JOIN loginUser ON user.loginID = loginUser.id RIGHT JOIN userRole ON user.roleID = userRole.id ORDER BY user.id DESC LIMIT 1"); return(newUser.ToList()); } }
public User Authenticate(string email, string password) { var user = _foosballContext.Users.SingleOrDefault(x => x.Email == email); string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: password, salt: user.HashSalt, prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8)); if (user == null || user.Password != hashed) { return(null); } // authentication successful so generate jwt token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim("UserID", user.UserID.ToString()), new Claim("Email", user.Email), new Claim("Role", user.Role) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); user.Token = tokenHandler.WriteToken(token); // remove password before returning user.Password = null; return(user); }
/// <summary> /// Returns a hashed representation of the supplied <paramref name="password"/>. /// </summary> /// <param name="password">The password to hash.</param> /// <returns>A hashed representation of the supplied <paramref name="password"/>.</returns> public virtual string HashPassword(string password) { if (password == null) { throw new ArgumentNullException(nameof(password)); } byte[] salt = new byte[_saltSize]; _rng.GetBytes(salt); byte[] subkey = KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA256, _iterCount, _subkeySize); byte[] passwordHash = new byte[13 + _saltSize + _subkeySize]; // Include format marker in case of future changes to hashing algorithm passwordHash[0] = 0x01; WriteNetworkByteOrder(passwordHash, 1, (uint)KeyDerivationPrf.HMACSHA256); WriteNetworkByteOrder(passwordHash, 5, (uint)_iterCount); WriteNetworkByteOrder(passwordHash, 9, (uint)_saltSize); Buffer.BlockCopy(salt, 0, passwordHash, 13, _saltSize); Buffer.BlockCopy(subkey, 0, passwordHash, 13 + _saltSize, _subkeySize); return(Convert.ToBase64String(passwordHash)); }
public static bool CheckPassword(string saltedHash, string passwordAttempt) { var parts = saltedHash.Split(':'); if (parts.Length != 2) { throw new ArgumentException("salted password format is wrong"); } var salt = Convert.FromBase64String(parts[0]); var attemptHash = Convert.ToBase64String(KeyDerivation.Pbkdf2( passwordAttempt, CreateCombinedSaltPepper(salt), KeyDerivationPrf.HMACSHA256, HashingIterations, HashBits / 8)); // Just to be safe, the slow compare method is used here, though it shouldn't matter if someone can use a // timing attack to determine how many characters they got right in the password *hash* return(SecurityHelpers.SlowEquals(parts[1], attemptHash)); }
public static string HashPassword(string password) { int iterCount = 10000; int saltLength = 128 / 8; // generate a 128-bit salt using a secure PRNG byte[] salt = new byte[saltLength]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(salt); } // derive a 256-bit subkey (use HMACSHA256 with 10,000 iterations) byte[] subkey = KeyDerivation.Pbkdf2( password: password, salt: salt, prf: KeyDerivationPrf.HMACSHA256, iterationCount: iterCount, numBytesRequested: 256 / 8); return(CreateHash(salt, subkey, iterCount, saltLength)); }