package com.qiankun.utils;

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

public class MD5 {

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

	private MD5() {

	}

	public static String digest(Object obj) {

		String buffer = obj.toString();
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");

			digest.update(buffer.getBytes());
			byte[] b = digest.digest();
			buffer = "";

			for (int i = 0; i < b.length; i++) {
				buffer += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
			}

		} catch (NoSuchAlgorithmException e) {
			throw new IllegalStateException("", e);
		}
		return buffer;
	}

	public static String digest16(String s) {
		return digest(s).substring(6, 24);
	}

	public static String digest(String s) {
		try {
			MessageDigest m = MessageDigest.getInstance("MD5");
			m.update(s.getBytes(), 0, s.length());
			return asHex(m.digest());
		} catch (NoSuchAlgorithmException e) {
			throw new IllegalStateException("", e);
		}

	}

	private static String asHex(byte hash[]) {
		char buf[] = new char[hash.length * 2];
		for (int i = 0, x = 0; i < hash.length; i++) {
			buf[x++] = HEX_CHARS[(hash[i] >>> 4) & 0xf];
			buf[x++] = HEX_CHARS[hash[i] & 0xf];
		}
		return new String(buf);
	}
	
	private static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','A', 'B', 'C', 'D', 'E', 'F' };
	public final static String encryption32(String s) {
		try {
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
