package com.blueland.core.util;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Md5Util {
	/**
	 * String转MD5
	 * @param psw
	 * @return
	 */
	private static Logger log = LoggerFactory.getLogger(Md5Util.class);
	public static String StringToMd5(String psw) {
        {
            try {
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                md5.update(psw.getBytes("UTF-8"));
                byte[] encryption = md5.digest();
 
                StringBuffer strBuf = new StringBuffer();
                for (int i = 0; i < encryption.length; i++) {
                    if (Integer.toHexString(0xff & encryption[i]).length() == 1) {
                        strBuf.append("0").append(Integer.toHexString(0xff & encryption[i]));
                    } else {
                        strBuf.append(Integer.toHexString(0xff & encryption[i]));
                    }
                }
 
                return strBuf.toString();
            } catch (NoSuchAlgorithmException e) {
                return "";
            } catch (UnsupportedEncodingException e) {
                return "";
            }
        }
	}
	public static String getPhpMd5(byte[] buffer) {
		String s = null;
		MessageDigest md = null;

		char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			log.error("getPhpMd5:buffer="+buffer,e);
			return null;
		}
		md.update(buffer);
		byte[] datas = md.digest(); // 16个字节的长整数
		char[] str = new char[2 * 16];
		int k = 0;
		for (int i = 0; i < 16; i++) {
			byte b = datas[i];
			str[k++] = hexChars[b >>> 4 & 0xf];// 高4位
			str[k++] = hexChars[b & 0xf];// 低4位
		}
		s = new String(str);
		return s;
	}
	
}
