Thursday, June 23, 2011

How to Do Hashing String with SHA-256

It will use SHA-256 hashing algorithm to generate a hash value for a password “123456″.

package org.best.example;
 
import java.security.MessageDigest;
 
public class SHAHashingExample 
{
    public static void main(String[] args)throws Exception
    {
     String password = "123456";
 
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(password.getBytes());
 
        byte byteData[] = md.digest();
 
        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
 
        System.out.println("Hex format : " + sb.toString());
 
        //convert the byte to hex format method 2
        StringBuffer hexString = new StringBuffer();
     for (int i=0;i<byteData.length;i++) {
      String hex=Integer.toHexString(0xff & byteData[i]);
          if(hex.length()==1) hexString.append('0');
          hexString.append(hex);
     }
     System.out.println("Hex format : " + hexString.toString());
    }
}
Output
Hex format : 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
Hex format : 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92

3 comments:

Unknown said...

Nice algorithm. So, assuming you use it to encrypt passwords, how would you compare the entered password to the one stored in the database?

sasitamil said...

It seems you are so busy in last month. The detail you shared about your work and it is really impressive that's why i am waiting for your post because i get the new ideas over here and you really write so well.

Selenium training in Chennai
Selenium training in Bangalore
Selenium training in Pune
Selenium Online training

Revathi said...

A good blog always comes-up with new and exciting information and while reading I have feel that this blog is really have all those quality that qualify a blog to be a one.keep share!!!

Android Training in Chennai

Android Online Training in Chennai

Android Training in Bangalore

Android Training in Hyderabad

Android Training in Coimbatore

Android Training

Android Online Training