MD5

来源:互联网 发布:网络侵权起诉状 编辑:程序博客网 时间:2024/04/27 21:08

package com.idate.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

public class MD5Util {

 public static String encodePassword(String password, String algorithm) {
  byte[] unencodedPassword = password.getBytes();

  MessageDigest md = null;

  try {
   // first create an instance, given the provider
   md = MessageDigest.getInstance(algorithm);
  } catch (Exception e) {
   e.printStackTrace();
   return password;
  }

  md.reset();

  // call the update method one or more times
  // (useful when you don't know the size of your data, eg. stream)
  md.update(unencodedPassword);

  // now calculate the hash
  byte[] encodedPassword = md.digest();

  StringBuffer buf = new StringBuffer();

  for (int i = 0; i < encodedPassword.length; i++) {
   if ((encodedPassword[i] & 0xff) < 0x10) {
    buf.append("0");
   }

   buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
  }

  return buf.toString();
 }
 
 public static void main(String[] args) throws UnsupportedEncodingException {
  System.out.println(MD5Util.encodePassword("123456", "md5"));
 }
}