In .net how can i make a own Login + Register (hashing + salt)?

59 Views Asked by At

i would like to make a own Login + Register in .net.

The Register should hash the password and also add salt to it.

How could i make this without using identity?

  • It should hash a password in the register
  • it should be possible to verify user , using the same hashing method
  • and extra Salt should be used
1

There are 1 best solutions below

4
MogliMehmet On

After searching i found it -> for further Users here is it how it can work: The Register with hashing and salt:

const int HASH_SIZE = 32;
const int iterations = 35000;
HashAlgorithmName algorithm = HashAlgorithmName.SHA512;

public async void createNewUser()
{

        uSalt = RandomNumberGenerator.GetBytes(HASH_SIZE);

        string hashedPassword = HashPassword(uPass, uSalt);

        User user = new User
            {
                FirstName = uFirst,
                LastName = uLast,
                Email = uEmail,
                Password = hashedPassword,
                Salt = uSalt,
            };

        await userservice.AddUserAsync(user);
        NavManager.NavigateTo("/");
    }
  

public string HashPassword(string password, byte[] salt)
{
    var hash = Rfc2898DeriveBytes.Pbkdf2(
      Encoding.UTF8.GetBytes(password),
      salt,
      iterations,
      algorithm,
      HASH_SIZE
      );

    return Convert.ToHexString(hash);
}

And heres the Login = verify:

const int HASH_SIZE = 32;
const int iterations = 35000;
HashAlgorithmName algorithm = HashAlgorithmName.SHA512;

public async void login()
{

    User user = await userservice.GetUserAsync(Username);
    if (user != null)
    {
        bool isValid = VerifyPassword(Password, user.Password, user.Salt);
        if (isValid)
        {
            NavManager.NavigateTo(($"/MyRecipts/{user.FirstName}/{user.LastName}/{user.Id}"));
        }
        else
        {
            LoginWentWrong = true;
        }
    }
}

public bool VerifyPassword(string password, string hash, byte[] salt)
{
    var hashToCompare = Rfc2898DeriveBytes.Pbkdf2(password,
        salt,
        iterations,
        algorithm,
        HASH_SIZE);

    return CryptographicOperations.FixedTimeEquals(hashToCompare, Convert.FromHexString(hash));
}

Dont forget to add the Salt to the User Class as this Type:

        public required byte[] Salt { get; set; }   //save the Salt in the DB -> so it can be used again for verifying the user