Search This Blog

Java: generate MD5 hash from a string

package examples;

import java.security.MessageDigest;

public class DigestUtil {

 public static byte[] getDigest(String s, String algorithm) throws Throwable {

  MessageDigest md = MessageDigest.getInstance(algorithm);
  return md.digest(s.getBytes("UTF-8"));

 }

 public static void main(String[] args) throws Throwable {
  
  String s = "Hello world!";
  byte[] digest = getDigest(s, "MD5");
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < digest.length; i++) {
   sb.append(String.format("%x", digest[i]));
  }
  System.out.println("MD5 HASH: " + sb.toString());
 }

}

No comments:

Post a Comment