Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Using MD5 to Digest Clear Text

In Chapter: Networked Applications
Author: Colin Wilcox ('NavaronUK')
Published? true
FormatLanguage: WikiFormat


Sometime it is necessary to save or send free text in an encrypted from. Android provides a standard Java MD5 class to allow plaintext to be replaced with an MD5 digest of the original text. This is a one-way digest that is not believed to be easily reversible (if you need that, use Java Cryptography).


Below is a simple function that takes a free text string and digests it using MD5, returning the encrypted string as a return value


public static String md5(String s)
			// Create MD5 Hash 
			MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
			byte messageDigest[] = digest.digest(); 
			// Create Hex String 
			StringBuffer hexString = new StringBuffer();  
			for (int i = 0; i < messageDigest.length; i++)
				hexString.append(Integer.toHexString(0xFF & messageDigest[i])); 
			return hexString.toString();   
		catch (NoSuchAlgorithmException e)
		return "";