问题
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.
回答1:
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]));
}
}
回答2:
The problem turned out to be the prefix $2y
in the hash. This is supposed to represent a version of the BCrypt algorithm but, according to Wikipedia, the prefix is not standard. To be clear, that online generator isn't using a non-standard algorithm, just a non-standard label.
Incidentally, the next section of the hash, $12
, indicates the number of rounds of hashing, and even though it's not the same as the Spring default (10 rounds), it doesn't cause the problem.
The solution is to simply change the y
for an a
. $2a
is the standard prefix for a BCrypt hash. You don't need to find a different BCrypt generator or anything, just edit the string.
This works:
insert into users (username, password, enabled) values ('joe','$2a$12$XodbOuISPCPQijlY8MIRUepDeURhxDe09/4VQU0Cno5zkTEKjZouO',true);
来源:https://stackoverflow.com/questions/58607669/how-can-i-pre-generate-a-bcrypt-hashed-password-for-my-spring-boot-application