package com.bcxin.ins.third.tyx.pingan.util;

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

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;

public class PaMD5Util {
	private static Logger logger =  LoggerFactory.getLogger(PaMD5Util.class);

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

	public static void main(String[] args) {
		System.out.println(PaMD5Util.MD5("20121221"));
		System.out.println(PaMD5Util.MD5("SDFASF "));
	}

	public final static String MD5(String s) {
		try {
			byte[] btInput = s.getBytes();
		
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
		
			mdInst.update(btInput);
			
			byte[] md = mdInst.digest();
			
			return byteToHexString(md);
		} catch (Exception e) {
			logger.error("MD5转换失败：", e);
			return null;
		}
	}

	public static String MD5(File file) {
		FileInputStream fis = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			fis = new FileInputStream(file);
			byte[] buffer = new byte[2048];
			int length = -1;
			while ((length = fis.read(buffer)) != -1) {
				md.update(buffer, 0, length);
			}
			byte[] b = md.digest();
			return byteToHexString(b);
		} catch (Exception ex) {
			logger.error("MD5转换失败：", ex);
			return null;
		} finally {
			try {
				if(fis!=null){
					fis.close();
				}				
			} catch (IOException ex) {
				fis = null;
				logger.error("MD5转换失败：", ex);
			}
		}
	}

	private static String byteToHexString(byte[] tmp) {
		String s;
		
		char str[] = new char[16 * 2]; 
		
		int k = 0; 
		for (int i = 0; i < 16; i++) { 
			
			byte byte0 = tmp[i]; 
			str[k++] = hexDigits[byte0 >>> 4 & 0xf]; 
			
			str[k++] = hexDigits[byte0 & 0xf]; 
		}
		s = new String(str); 
		return s;
	}

}
