Walkthrough: Hashing and Salting Passwords

Setup

  1. Check out the rest-walkthrough-solution branch of LaunchCodeTraining/launchcart
  2. Create and checkout a story branch named securely-hash-passwords via $ git checkout -b securely-hash-passwords

Determine the Status of the Current Code

  1. Run tests to see current status
  2. Search for any //TODO comments

Implement Secure Password Hashing using BCrypt

Add the Spring Security dependency to build.gradle:

dependencies {
    compile('org.springframework.security:spring-security-crypto')
    //more dependencies will be listed above or below...
}

Use the BCryptPasswordEncoder Class

  1. Create a static final instance of the encoder class, within User:

    private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    
  2. Use BCryptPasswordEncoder.encode in the User.java contructor:

    public User(String username, String password) {
        this.username = username;
        this.pwHash = hashPassword(password);
    }
    
    private static String hashPassword(String password) {
        return encoder.encode(password);
    }
    
  3. Update isMatchingPassword(String password):

    public boolean isMatchingPassword(String password) {
        return encoder.matches(password, this.pwHash);
    }
    

Let’s see if it works!

  1. Make sure the tests pass
  2. Run bootRun and see if you can register (register a few users)
  3. Verify what the hashed and salted password looks like in the database

Quiz

  • Where is the salt stored?