Calculate MD5 for a String

 
import java.security.MessageDigest;

public class Main {
  public static void main(String[] argv){
    System.out.println(computeMD5("java2s"));
  }
  public static String computeMD5(String input) {
    MessageDigest digest;
    try {
      digest = MessageDigest.getInstance("MD5");
      digest.update(input.getBytes("UTF-8"));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    byte[] digestBytes = digest.digest();

    StringBuffer hexString = new StringBuffer();
    for (byte digestByte : digestBytes) {
      hexString.append(Integer.toHexString(0xFF & digestByte));
    }
    return hexString.toString();

  }

}
  

Output:


df6d7345df5576959410647cbfaff
Home 
  Java Book 
    Runnable examples  

Security:
  1. Calculate checksums for a range of bytes.
  2. Calculate MD5 for a String
  3. Calculate MD5 for a Stream