package com.shanghaichengdi.ghjgitem.util;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

public class AuthUtils {
	public static String getSign(Map<String, String> headers, String secretKey) throws IOException {
		//1. 参数字典顺序进行排序
		TreeMap<String, String> sortedMap = sortByKey(headers);

		//2.去掉排序后的参数的连接符'&'，并在末尾追加secret_key
		String joinStr = join(sortedMap, secretKey);
		//3. md5加密
		return EncrptUtils.md5Encode(joinStr);
	}

	private static TreeMap<String, String> sortByKey(Map<String, String> headers) {
		TreeMap<String, String> sortedMap = new TreeMap<String, String>();
		if( headers != null ) {
			for(Map.Entry<String, String> entry : headers.entrySet()) {
				sortedMap.put(entry.getKey(), entry.getValue());
			}
		}
		return sortedMap;
	}

	private static String join(Map<String, String> paramsMap, String secretKey) throws IOException{
		StringBuffer sb = new StringBuffer();
		for(Map.Entry<String, String> entry : paramsMap.entrySet()) {
			sb.append(entry.getKey()).append("=").append(entry.getValue());
		}

		sb.append(secretKey);
		return sb.toString();
	}
}
