Integrating BCrypt Hashing With Hibernate Framework

In this example, im trying to simulate a simple login to MySQL database. Usually i hash password value using MD5, but now im trying to do hashing using BCrypt Algorithm. Im using a simple java BCrypt class downloaded from here.

First as always, a simple table and row.

CREATE TABLE `users` (
  `username` varchar(20) NOT NULL DEFAULT '',
  `pwd` varchar(80) DEFAULT NULL,
  PRIMARY KEY (`username`)

insert into `users`(`username`,`pwd`) values ('edwin','$2a$12$bUwElzXYO116G6x.fLm5FOAJNB46R0974sAh2TQumJei4ia.x0YPy');

Next is creating a simple java class and xml to represent database tables.

package com.edw.bean;

public class Users  implements {

     private String username;
     private String pwd;

    public Users() {

	// other setter and getter
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    <class name="com.edw.bean.Users" table="users" catalog="test">
        <id name="username" type="string">
            <column name="username" length="20" />
            <generator class="assigned" />
        <property name="pwd" type="string">
            <column name="pwd" length="80" />

Next is my hibernate.cfg.xml configuration

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "">
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">****</property>
    <mapping resource="com/edw/bean/Users.hbm.xml"/>

And my java class to load hibernate.cfg.xml

package com.edw.util;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;
    static {
        try {           
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {            
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
    public static SessionFactory getSessionFactory() {
        return sessionFactory;

And this is my Main java class,

package com.edw.main;

import com.edw.bean.Users;
import com.edw.util.BCrypt;
import com.edw.util.HibernateUtil;
import org.apache.log4j.Logger;
import org.hibernate.Session;

public class Main {
    private static Logger logger = Logger.getLogger(Main.class );
    private Boolean startApp(String username, String password) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            Users user = (Users)session.createQuery("from Users where username = :username")
                    .setString("username", username)
            // compare password with database's encrypted password
            if(BCrypt.checkpw(password, user.getPwd()))
                return true;
            return false;
        } catch (Exception e) {
        } finally {            
        return false;
    private String hashPassword(String password) {
        return BCrypt.hashpw(password, BCrypt.gensalt(12));
    public static void main(String[] args) {
        Main main = new Main();
        boolean success = main.startApp("edwin", "12345");
            logger.debug("Password is Right");
            logger.debug("Password is Wrong");
        // simulate 10 hashed string password
        for (int i = 0; i < 10; i++) {

This is my Netbeans project structure,

And this is my Netbean’s console


No Comments

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked

:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)