1 mport java.security.MessageDigest; 2 import java.security.NoSuchAlgorithmException; 3 4 public class CreateMD5 { 5 6 //静态方法,便于作为工具类 7 public static String getMd5(String plainText) { 8 try { 9 MessageDigest md = MessageDigest.getInstance("MD5"); 10 md.update(plainText.getBytes()); 11 byte b[] = md.digest(); 12 13 int i; 14 15 StringBuffer buf = new StringBuffer(""); 16 for (int offset = 0; offset < b.length; offset++) { 17 i = b[offset]; 18 if (i < 0) 19 i += 256; 20 if (i < 16) 21 buf.append("0"); 22 buf.append(Integer.toHexString(i)); 23 } 24 //32位加密 25 return buf.toString(); 26 // 16位的加密 27 //return buf.toString().substring(8, 24); 28 } catch (NoSuchAlgorithmException e) { 29 e.printStackTrace(); 30 return null; 31 } 32 33 } 34 35 public static void main(String[] args) { 36 //测试 37 System.out.println(CreateMD5.getMd5("hello")); 38 } 39 40 }