Sunday, July 29, 2012

Generating Hash in java using own salt

Generating hash value in java is very tedious task but it is very useful where we use random password or add some unique string with image name.In java, java.security provides differnet type of class and method for hash function.Salt is a value which helps in generate unique hash value .
I'm using MD5 with ShA-1 here.


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
public class OwnHash{
public String generateHash(String input)
    {
        StringBuilder hash = new StringBuilder();
        String SALT = "vaaabbccddeeff";
        String NEWPASSWORD=SALT+input;

        try {
            MessageDigest sha = MessageDigest.getInstance("SHA-1");
            byte[] hashedBytes = sha.digest(NEWPASSWORD.getBytes());
            char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                    'a', 'b', 'c', 'd', 'e', 'f' };
            for (int idx = 0; idx < hashedBytes.length; ++idx)
            {
                byte b = hashedBytes[idx];
                hash.append(digits[(b & 0xf0) >> 4]);
                hash.append(digits[b & 0x0f]);

            }
        }
        catch (NoSuchAlgorithmException e)
        {
            // handle error here.
        }

        return hash.toString();
    }}

Mysql-JDBC connection in java

In java , jdbc connection is very simple , just add a mysql jar file in lib folder and make special class which return Connection type reference .in this example i'm using properties file to pass user name and password.
This is type 4 driver example bcoz it uses java  code to access data from MySql,

public Connection getdbConnection()
{
try {
   Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException ex) {
   System.out.println("Error: unable to load driver class!");
   System.exit(1);
}
String URL = "jdbc:mysql://localhost:3306/";
Properties info = new Properties( );
info.put( "user", "username" );
info.put( "password", "password" );

Connection conn = DriverManager.getConnection(URL, info); 

return conn;
}
 
Complete Code is here :
 
import java.io.IOException;
import java.sql.*;


public class DBUtil {
 static Connection cn=null;
 
 public  Connection getConnect()
 {
   
   
  try {
   Class.forName("com.mysql.jdbc.Driver");
cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","admin");
  } 
  catch(ClassNotFoundException se)
  {
   se.printStackTrace();
  }
  catch (SQLException e1) 
  {
   e1.printStackTrace();
  }
  return cn; 
 }
 
 

}