0

I want to use password encryption before it will be saved in mySQL. For this school project, i am using Spring boot mvc together with hibernate. What is the best and simplest way to do it? I am new to Java, spring boot, hibernate. Any help will be appriciated.

Abinn007
  • 9
  • 2

1 Answers1

0

You can use Bcrypt hashing instead of encyption. Check differece between hashing and encryption link

  1. You need to create bean of BcryptPasswordEncoder

    @Bean BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); }

  2. Now autowire the bcrypt bean

    @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder;

  3. Use the bcryptencoder to ecode the password before saving to database

    User user = new User(); user.setUserName("username"); user.setPassword(bCryptPasswordEncoder.encode("userpassword"));

So the, overall code

//class that handles saving/registering
public class UserRegister{

        @Autowired
        private BCryptPasswordEncoder bCryptPasswordEncoder;

        @Autowired
        private userRepository userRepository; 

        public void register() {
            User user = new User();
            user.se`enter code here`tUserName("username");
            //encodes the password
            user.setPassword(bCryptPasswordEncoder.encode("userpassword"));
            //saves to database
            userRepository.save(user);
        }

}