MD5 in Java

The MD5 or Message-Digest Algorithm is a commonly used hash function, which produces a 128 bit hash value, commonly expressed as a 32 digit hex number. It is commonly used by web developers to store passwords or sensitive information in their databases. It is to be noted that an MD5 string cannot be converted back into the original string.
Although this hashing method is now considered "cryptographically broken or not suitable for further use" as of 2005, it is still widely used. In PHP, performing MD5 is very simple - one just has to call a function with the message to be digested as the argument($digest = md5("message"); ). But it is not that simple in java.

Here is a java class which you can place in your project to perform MD5 hashing.


public class MD5
public static final String salt = "aq32nngetg45678";

public static String getMd5(String value)
 char[] hexDigits =  {'0','1','2','3','4','5','6','7','8','9','a','b','c','d' ,'e','f'};
 MessageDigest md5 = MessageDigest.getInstance("MD5");
 byte[] messageDigest = md5.digest();
 StringBuilder sb = new StringBuilder(32);

 for (byte b : messageDigest) //for zero padding, ie make '1' '01'
   sb.append(hexDigits[(b >> 4) & 0x0f]); //0x0f in hex = 15 in decimal. If b=1
   sb.append(hexDigits[b & 0x0f]);// sb += hexDigits[0] + hexDigits[1](sb += "01")
 return sb.toString();
catch(Exception e)
 return "ERROR";

After placing this class in your project, you can perform md5 hashing by
String digest = MD5.getMd5("message");
It is a good practice to append a random string to your original string before performing hashing. This random string is called 'salt'. Salt is added to prevent dictionary attacks and rainbow table attacks.

>> is the signed right shift operator and it shifts a bit pattern to right. Its syntax is bit_pattern_to_shift >> no_of_positions_to_shift. Hence, here, before placing a digit into the final string,it is padded.