[JAVA] Password hashing and authentication using JBcrypt

What i did

I used JBcrypt in Java (Spring) to hash the password and authenticate it.

Preparation

Get the jar file from MVN REPOSITORY

Password hashing


@PostMapping("/sample")
public String sample(@Validated SampleForm sampleForm,
	BindingResult bindingResult, Model model) {

        //Convert input value password to hash value
	String hashedCode = BCrypt.hashpw(sampleForm.getPassword(), BCrypt.gensalt());

        //The process of storing the hashed password in the DB below

        ...
}

Salt is a string that is attached before and after the password before it is put into the hash function. [Quoted from IT Glossary that makes you feel like you understand even if you don't understand

Password authentication


@Override
public boolean isPasswordCorrect(String inputPassword) {

        final String SAMPLE_SQL = "SQL statement listed here"

        //Get password from DB
        Map<String, Object> PasswordFromDB = jdbcTemplate.queryForMap(SAMPLE_SQL);
        String passwordFromDB = (String)PasswordFromDB.get("password");

        //Compare the plaintext inputPassword that is the input value with the hashed passwordFromDB in the DB
        if(BCrypt.checkpw(inputPassword, passwordFromDB)) {
            //processing
	    }
}

Summary

Easy to hash!

When hashing


BCrypt.hashpw(The value you want to hash, BCrypt.gensalt());

When authenticating a hashed value,


BCrypt.checkpw(Plaintext values you want to compare,Hashed value obtained from DB);

that's all. Thank you for reading to the end.

Recommended Posts

Password hashing and authentication using JBcrypt
[Rails] Google, Twitter, Facebook authentication using Devise and Omniauth
SNS authentication using Rails google
Signing and validation using java.security.Provider
Animation using matchedGeometryEffect and @Namespace
Access denied for user'root' @'localhost' (using password: YES) and gave up
Scala: HMAC SHA-1 Hashing and Base64 Encording for CloudStack API Authentication