Java Password Hashing (Bcrypt)


This article is an extension of the Python Password Hashing article which explains some of the flaws in traditional password hashing and how it can be mitigated with salting. The article can be found here: https://vinsloev.blogspot.com/2019/07/python-password-hashing-bcrypt.html

As an introduction to this article a short explanation of password hashing in general can be found below.

A hash is designed to act as ”one-way-function” making it easy to perform but very hard to reverse. The reason why this is so beneficial when it comes to password managing and login handling, is because it allows the developers to convert the original password into a unique phrase that can be stored in the database. By using a hash function the application don’t have to match the original password in clear text with the password given upon login as it does not know what that password is. Instead it only need to know what hashing function where used and then see if the password entered generates the same hash value as the one saved in the database. This little trick provides the same login functionality as when all passwords were in clear text but the difference here is that now it’s only the user who knows exactly what the password is.

With a firm understanding of Password Hashing its time to see how such can be utilized in Java using the Bcrypt library. 

First we will create a Class called bcrypt with the following code:
import org.springframework.security.crypto.bcrypt.BCrypt;
public class bcrypt {
    private String password = "thomas123";
    private String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt(10));
    public void checkPass(String password) {
        if(BCrypt.checkpw(password, hashedPassword)) {
            System.out.println("Match");        } else {
            System.out.println("No Match");        }
    }

}

In the above code we have declared a variable called password, which is the password we are going to hash, next we call the BCrypt.hashpw() method using the declared password and a generated salt value. 

Following the hashedPassword variable we creates a method called checkPass with a simple conditional statement that will output a valued based on wether the password we give as a input parameter matched the one we hashed.

The last thing we have to do is then to call our checkPass method with a String value.

public class main {

    public static void main(String [] args)
    {
        bcrypt bcrypt = new bcrypt();        bcrypt.checkPass("thomas123");    }
}

Using the above main class our output is evaluated to "Match" since both the hashed password and inputted parameter value are identical.

Kommentarer

Populære opslag fra denne blog

Artificial Intelligence - How it could lead to a greener and healthier world

Uber Technology Stack

REST API (Web API) Part 2 - Security