package com.njcn.utils;

import com.njcn.serviceimpl.weeklyreport.WeeklyReportDataServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class MD5 {
	private static final Logger logger = LoggerFactory.getLogger(MD5.class);
	static char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	
	public static String getMD5(String str) {
		String s = null;
		char[] charArr = str.toCharArray();
		byte[] byteArr = new byte[charArr.length];
		
		for(int i = 0; i < charArr.length; i++) {
			byteArr[i] = (byte)charArr[i];
		}
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] md5Bytes = md.digest(byteArr);
			s = byteToHexString(md5Bytes);
		} catch (NoSuchAlgorithmException e) {
			logger.error(e.getMessage());
		}
		return s;
	}
	
	private static String byteToHexString(byte[] tmp) {
		char[] str =new char[16 * 2]; // 每个字节用 16 进制表示的话，使用两个字符，
		int k = 0;
		for (int i = 0; i < 16; i++) {
			byte b = tmp[i];
			str[k++] = hexdigits[b >>> 4 & 0xf]; //取字节中高4位的数字转换
			str[k++] = hexdigits[b & 0xf]; //娶字节中低4为的数字转换
		}
		String s = new String(str);
		return s;
	}
	
	public static String twiceMD5(String str) {
		return MD5.getMD5(MD5.getMD5(str));
	}
}
