Using BCryptPasswordEncoder to encrypt your passwords

In this tutorial we will learn how to generate encrypted passwords using BCryptPasswordEncoder.

The BCryptPasswordEncoder can be used to generate encrypted password with a random salt. This means that each call will have a different result, and so we need to only encode the password once.

Here is a sample Java class which generates a BCrypt encoded Password for two Strings:

package com.example.testrest;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class MyEncoder {
  public static void main(String[] args) {
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    String encoded = encoder.encode("password1");
    System.out.println(encoded);
    encoded = encoder.encode("password2");
    System.out.println(encoded);
  }
}

Mind it however that the BCrypt algorithm generates passwords with a length of 60, therefore make sure that you define your database columns (where you store the password) with the appropriate length.

If you want to generate the password as part of a Registration process, make sure to add in your Configuration Bean:

@Bean public PasswordEncoder passwordEncoder() {
  return new BCryptPasswordEncoder();
}

Then, in the Controller method which manages user storage:

@Autowired private PasswordEncoder passwordEncoder;
@Override public User registerNewUser(User user) {
  String clearTextPassword = user.getPassword();
  user.setPassword(passwordEncoder.encode(clearTextPassword));
  return repository.save(user);
}

If you want a full example application which uses the BCryptPasswordEncoder then check this tutorial: Securing Spring Boot applications with JDBC Authentication