I am using Spring MVC and I want to encrypt the password that gets saved in dB, I had a look into other threads and they suggest going with MD5. Is it a good practice to go with MD5 or is there any other method in Spring to achieve it?
4 Answers
You can use BCryptPasswordEncoder
to encode your password, in order to do that you will need to create a bean of this class.
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
And while registering (saving new user to database) your user, you can auto wire PasswordEncoder
and call encode
method to encode your password
@Autowired PasswordEncoder passwordEncoder;
public User registerUser(User user){
// other logic
String encryptedPassword = passwordEncoder.encode(user.getPassword());
user.setPassword(encryptedPassword);
//logic to save the user to DB
}
-
1Thanks for your answer but I cannot understand, if I encrypted password by this way how the password can match when I trying to login ? Because if I'm not wrong 'BCryptPasswordEncoder' all time generating different value.By the way I'm new to Spring :) Apr 5, 2017 at 0:39
-
When you are trying to login and if you are passing password to login method as a simple text, then you will need to call again the encode method on the password user have provided while logging and then compare Apr 5, 2017 at 12:21
Can you clarify if you are looking for Spring Security or Spring MVC. Your question title is ""Password encryption in "Spring MVC" whereas you have tagged the question for Spring Security.
Spring security suggests to use the following org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
-
1
-
Great, I have shared the relevant link from Spring reference pages. If you need any help add a comment.– bhrtFeb 26, 2017 at 6:47
Don't use MD5, the problem with MD5 hashing is that it is relatively quick to do and if someone gets hold of the hashes they can brute force it pretty easily. There are also rainbow tables which are lists of passwords with their associated MD5 hashes.
As @Jan Nielsen suggests, BCrypt is far superior. I personally use PBKDF2. Both these approaches work by using a random salt while generating the hash. In the database you store the salt and the hashed password. I like to go one step further and also store the number of iterations that was used to create the hash.
Here is a good blog on password encryption that covers the details in more depth with code samples. https://crackstation.net/hashing-security.htm