MD5摘要

package com.tarena.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

 public class MD5Util {
  /**
   * 将原文str经过MD5摘要算法得到密文
   * @param str 如: 1234
   * @return "1234" 的摘要
   */
  public static String md5(String str){
    try {
      MessageDigest md = MessageDigest.getInstance("MD5");
      md.update(str.getBytes());
      byte[] md5 = md.digest();
      char[] ch = "0123456789abcdef".toCharArray();
      StringBuilder buf = new StringBuilder();
      for (byte b : md5) {
        buf.append(ch[ b>>>4 & 0xf ]);
        buf.append(ch[ b& 0xf ]);
      }
      return buf.toString();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }
  
  public static void main(String[] args) {
    System.out.println(md5("1234"));
  }
}

你可能感兴趣的:(MD5)