How to get the SHA1 hash sum of a String in Android

Here’s one piece of code that comes very handy in some situations, just copy and paste this to get the SHA1 hash sum from a text String. The Hash is returned as an hex encoded human readable String, see below for an example of use:


 /**
  * Returns the SHA1 hash for the provided String
  * @param text
  * @return the SHA1 hash or null if an error occurs
  */
  public static String SHA1(String text) {
    	
  try {
    		
    MessageDigest md;
    md = MessageDigest.getInstance("SHA-1");
    md.update(text.getBytes("UTF-8"), 
              0, text.length());
    byte[] sha1hash = md.digest();
			
    return toHex(sha1hash);
			
  } catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
  } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
  }
    	
  return null;
}
	
public static String toHex(byte[] buf) {
		
  if (buf == null) return "";

  int l = buf.length;
  StringBuffer result = new StringBuffer(2 * l);

  for (int i = 0; i < buf.length; i++) {
    appendHex(result, buf[i]);
  }

  return result.toString();

}
	
private final static String HEX = "0123456789ABCDEF";
	
private static void appendHex(StringBuffer sb, byte b) {

  sb.append(HEX.charAt((b >> 4) & 0x0f))
    .append(HEX.charAt(b & 0x0f));

}

Here’s how to use this, just an example:


String test = new String("Hello World");
Log.e(TAG, "String: " + test);
String SHA1 = SHA1(test);
Log.e(TAG, "SHA1 HASH: " + SHA1);

The code above will print this output:

String: Hello World
SHA1 HASH: 0a4d55a8d778e5022fab701977c5d840bbc486d0

Enjoy 😉

Advertisements

3 thoughts on “How to get the SHA1 hash sum of a String in Android

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s