package com.xxfc.platform.universal.weixin.util;

import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;

/**
 *
 */
@Slf4j
public class WeChatSignUtil {

	/**
	 *
	 * @param signParamMap
	 * @param keyValue
	 * @return
	 */
	public static String getMD5Sign(Map<String, String> signParamMap, String keyValue) {
		StringBuilder sb = new StringBuilder();
		ArrayList<String> keyList = new ArrayList<String>(signParamMap.keySet());
		Collections.sort(keyList);
		for (String key : keyList) {
			String value = signParamMap.get(key);
			if (!"".equals(value) && !"key".equals(key) && !"sign".equals(key)) {
				sb.append(key).append("=").append(value).append("&");
			}

		}
		sb.append("key=").append(keyValue);
		return getMD5(sb.toString()).toUpperCase();
	}


	/**
	 * MD5
	 */
	private static final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
			'F' };

	public static String getMD5(String inStr) {
		byte[] inStrBytes = null;
		try {
			inStrBytes = inStr.getBytes("utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		try {
			MessageDigest MD = MessageDigest.getInstance("MD5");
			MD.update(inStrBytes);
			byte[] mdByte = MD.digest();
			char[] str = new char[mdByte.length * 2];
			int k = 0;
			for (int i = 0; i < mdByte.length; i++) {
				byte temp = mdByte[i];
				str[k++] = hexDigits[temp >>> 4 & 0xf];
				str[k++] = hexDigits[temp & 0xf];
			}
			return new String(str);
		} catch (NoSuchAlgorithmException e) {
			log.error(e.getMessage(), e);;
		}
		return null;
	}
}
