package com.uas.eis.utils;

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

public class MD5Util {

	public static String MD5(String plainText) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			try {
				md.update(plainText.getBytes("UTF8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer(200);
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset] & 0xff;
				if (i < 16) buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			return buf.toString();
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("MD5加密出现错误");
		}
	}

	public static String getMD5(String str) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			return new BigInteger(1, md.digest()).toString(16);
		} catch (Exception e) {
			throw new RuntimeException("MD5加密出现错误");
		}
	}

	/**
	 * MD5加密
	 * @param message
	 * @return
	 */
	public static String getEncryption(String message){
		String result = "";
		if(message != null){
			try {
				MessageDigest md = MessageDigest.getInstance("MD5");		//指定加密方式
				//加密
				byte[] bytes = md.digest(message.getBytes());
				for(int i = 0; i < bytes.length; i++){
					// 将整数转换成十六进制形式的字符串 这里与0xff进行与运算的原因是保证转换结果为32位
					String str = Integer.toHexString(bytes[i] & 0xFF);
					if(str.length() == 1){
						str += "F";
					}
					result += str;
				}
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}	
		}
		return result;
		
	}
}
