Storing passwords in plain text in databse is vulnerable to security. This article is about storing hashed password to databse in java. Doing so it becomes impossible for even BDAs to extract the real passwords. There are many hashing algorithms such as MD5, SHA-1, SHA-2 etc to hash a password but adding a salt to the password provides extra security. In this article we will be using jBCrypt, which internally generates a random salt while encoding passwords, to encode our plain text passwords and store in DB.
In this article, we will be using spring MVC and hibernate just to get rid of some configurations to connect with DB. The main focus here will be to use jBCrypt to encode the plain text passwords and save to DB and again how can we match the hashed password with the plain text password. Here we will be creating a simple app that encryptes password before storing user details in the DB.
As per wiki, bcrypt is a password hashing function designed by Niels Provos and David Mazières, based on the Blowfish cipher. Bcrypt uses adaptive hash algorithm to store password.BCrypt internally generates a random salt while encoding passwords and hence it is obvious to get different encoded results for the same string.But one common thing is that everytime it generates a String of length 60.
Following is the maven dependency required to get started using Bcrypt.pom.xml
Bcrypt library provides ready made implementation to hash plain text password. The method
hashpw() requires plain text password and random salt to hash a plain text password. Following is the implementation.The
save() method defined in the
UserServiceImpl.java internally calls following method to encrypt the password before saving it to the DB.
Following is the implementation that actually matches the plain text and encrypted password.
Here first we will save a user in the db. The service implementation will encrypt the password before saving to DB. Then we will fetch the same user from DB and try to match the enccrypted password with the plain text password and display the result.
Following is the entry created in databse after executing above test.
I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.
Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.
©2017, DevGlan. All Rights Reserved.
Contact us: firstname.lastname@example.org