Social Icons

Sunday, April 4, 2010

How to hash a given string | java | Complete code


In reference to the original post.. complete code goes here.

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