Search code examples
spring-bootbcryptpassword-hash

How can I pre-generate a BCrypt hashed password for my Spring Boot application?


I have a Spring Boot application (code here) with a security configuration that utilizes a BCryptPasswordEncoder:

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

I'd like to pre-generate a couple of passwords to initialize my database, for testing or for logging in on a developer machine. (Not for production.) My database is PostgreSQL and the schema is based on the Spring Security default schema, with a users table and an authorities table. My SQL statement looks like this:

insert into users (username, password, enabled) values ('joe','$2y$12$XodbOuISPCPQijlY8MIRUepDeURhxDe09/4VQU0Cno5zkTEKjZouO',true);

I don't know much about how the BCrypt hashing algorithm works, but I generated this password hash (for the password "test") using a free online BCrypt hash generator that looks legitimate. Nevertheless, I cannot log in to my Spring Boot application. The error in the logs is "bad credentials". What gives?

PS: This is a follow-up to this other question.


Solution

  • You can use online BCrypt generator but the thing is that the online generator might generate different regex from your Spring Segurity enconder.

    For example the online generator can generate BCrypt with regex “$2y” and your Spring Boot enconder generate with “$2a” regex. If this happen you will get always bad credencials.

    I strongly recommend you to generate your passwords using Spring Boot BCrypt Enconder.

    @SpringBootApplication
    public class QuartzJdbcJobStoreBciApplication extends SpringBootServletInitializer{
    
    public static void main(String[] args {
        SpringApplication.run(QuartzJdbcJobStoreBciApplication.class, args);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password [] = {"Password1", "Password2", "Password3"};
        for(int i = 0; i < password.length; i++)
            System.out.println(passwordEncoder.encode(password[i]));
    
        }
    }