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

Author: Colin Wilcox
Published? true -- FormatLanguage: W

Problem:

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).

Solution:

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

Discussion:

public static String md5(String s)
	{ 
		try
		{ 
			// Create MD5 Hash 
			MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
			digest.update(s.getBytes()); 
			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)
		{
			e.printStackTrace(); 
		}
		
		return "";
	}
No records found.