package com.offcn.api.nwn.md5;

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

public class LMFMD5 {
    //����һ����LMFMD5
    public static String MD5(String str) {
    	
    	/*
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
         // ����һ��MD5���ܼ���ժҪ
            md.update(sourceStr.getBytes());
         // ʹ��ָ����byte�������ժҪ
            byte b[] = md.digest();
         // ������ת����ʮ�����Ƶ��ַ�����ʽ
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
            System.out.println("MD5(" + sourceStr + ",32) = " + result);
         //   System.out.println("MD5(" + sourceStr + ",16) = " + buf.toString().substring(8, 24));
            // ע�͵���md5��16λȡֵ
        } catch (NoSuchAlgorithmException e) {
            System.out.println(e);
        }
        return result;*/
    	
    	
    
            MessageDigest messageDigest = null;
            try {
                messageDigest = MessageDigest.getInstance("MD5");
                messageDigest.reset();

                messageDigest.update(str.getBytes("UTF-8"));
            } catch (NoSuchAlgorithmException e) { // NOSONAR
                System.out.println(e.getMessage());
            } catch (UnsupportedEncodingException e) { // NOSONAR
                System.out.println(e.getMessage());
            }

            byte[] byteArray = messageDigest.digest();

            StringBuffer md5StrBuff = new StringBuffer();

            for (int i = 0; i < byteArray.length; i++) {
                if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                    md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
                else
                    md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
            }

//            return md5StrBuff.toString().toUpperCase();
            return md5StrBuff.toString();
        
        
    }
}

