Outline

Demo: Use Cryptography To Encrypt Password

In Conduit.Repositories Project

Modify AccountRepository.RegisterUserAsync method
  • Call a non-existing method called CreateAccount
  • Pass the register object as a parameter
  • Assigned its return value to a local variable Type Account
  • Let the IDE generate the method for you
Modify AccountRepository.CreateAccount method
  • Create 2 byte array variables to hold the password hash & salt
  • Call a non-existent method called CreatePasswordHash
  • Pass in the plain text password along with the variables for hash & salt as out paramters
Modify Account.Repository.CreatePasswordHash
  • In using statement, create an instance of the HMACSHA512 class
  • Assign the HMAC Key to the salt
  • Using the HMAC object compute the password hash

Here is the code for AccountRepository.UserExistAsync method:

        public async Task<User> RegisterUserAsync(Register register)
        {
            bool userExist = await UserExistAsync(register);
            if (userExist)
            {
                throw new UserExistException("The email or user name is already in use.");
            }
            Account account = CreateAccount(register);
            User user = new User
            {
                Bio = "no bio yet",
                Email = register.Email,
                Image = "no image yet",
                Token = "no token yet",
                UserName = register.UserName
            };
            return user;
        }

Here is the code for the AccountRepository.CreateAccount method:

        private Account CreateAccount(Register register)
        {
            byte[] passwordHash, passwordSalt;
            CreatePasswordHash(register.Password, out passwordHash, out passwordSalt);
        }

Here is the code the AccountRepository.CreatePasswordHash method:

        private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
        {
            using (var hmac = new HMACSHA512())
            {
                passwordSalt = hmac.Key;
                passwordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password));
            }
        }