Social Icons

Monday, March 29, 2010

How to Hash a given String using Java | Complete Code


In reference to the original post. Here is the Complete code for the task.

  1: import java.security.MessageDigest;
  2: import java.security.NoSuchAlgorithmException;
  3: import java.io.UnsupportedEncodingException;
  4: 
  5: class HashMe {
  6:     
  7:     
  8:  public byte[] getHash(String password) 
  9: 
 10: throws NoSuchAlgorithmException , UnsupportedEncodingException
 11:  {
 12:        /* invoke MessageDigest class's static methos getInstance to
 13:         * implement the specified
 14:         * hashing algoeithems , note that the arguments 
 15:         * passed in this method are case insensitive
 16:         */
 17:        MessageDigest digest = MessageDigest.getInstance("SHA-1");
 18:        /* Reset the Digest in case The digest currently holds 
 19:          a value in it*/
 20:        digest.reset();
 21:        /* MessageDigest.digest method finalizes the hasing 
 22:         process as returns
 23:         the Hash value as a byte array*/
 24: 
 25:        byte[] input = digest.digest(password.getBytes("UTF-8"));
 26:        return input;
 27:  }
 28: 
 29:  public byte[] getHash(String password, byte[] salt) throws 
 30: 
 31: NoSuchAlgorithmException,UnsupportedEncodingException {
 32: 
 33:        /* We use a different hasing Algorithem this time*/
 34:        MessageDigest digest = MessageDigest.getInstance("SHA-256");
 35:        digest.reset();
 36:        /* MessageDigest.update method updates the current 
 37:            digest with the supplied salt value
 38:           It doesnt finish the hasing process we sill have 
 39:         to invoke digest method */
 40: 
 41:        digest.update(salt);
 42:        return digest.digest(password.getBytes("UTF-8"));
 43:  }
 44: 
 45:  public byte[] getHash(int iterationNb, String password, byte[] salt) 
 46: 
 47: throws NoSuchAlgorithmException , UnsupportedEncodingException
 48: {
 49:        MessageDigest digest = MessageDigest.getInstance("SHA-1");
 50:        digest.reset();
 51:        digest.update(salt);
 52:        byte[] input = digest.digest(password.getBytes("UTF-8"));
 53:     
 54:        /* Up to this point we have now a hash value for the given 
 55:           string but further improvise
 56:           the Invulnerbility of the hash value we repeat the hasing 
 57:             process for number of times which
 58:           the method has recived as a parameter
 59:        */
 60: 
 61:        for (int i = 0; i < iterationNb; i++) {
 62:            digest.reset();
 63:            input = digest.digest(input);
 64:        }
 65:        return input;
 66:    }
 67:     
 68: }
 69: 
 
 
Blogger Templates http://slots.to/