hashing Posts

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 java.io.Serializable {

     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" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <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

Creating an MD5 String using Java

MD5 is a simple cryptographic hashing algorithm widely used for various application. In this tutorial im trying to generate MD5 value from a string and then compare it to mysql’s MD5 query result.

This is my java code to generate MD5, im using java’s MessageDigest.

package com.edw.util;

import java.security.MessageDigest;
import org.junit.Test;

 * @author edw
public class MD5Test {

    public MD5Test() {

    public String hexStringFromBytes(byte[] b) {
        char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        String hex = "";
        int msb;
        int lsb = 0;
        int i;

        for (i = 0; i < b.length; i++) {
            msb = ((int) b[i] & 0x000000FF) / 16;
            lsb = ((int) b[i] & 0x000000FF) % 16;
            hex = hex + hexChars[msb] + hexChars[lsb];
        return hex;

    public void testMD5() throws Exception {
        MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
		// get md5 for word "PASSWORD"
        byte[] passwordBytes = digest.digest();

		// result = 319f4d26e3c536b5dd871bb2c52e3178

compared to mysql’s md5 function

you can see that MD5 strings generated by java and mysql are both the same.