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();
    }}

No comments:

Post a Comment