package com.friday.custody.service.trustService.csc.utils;

import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Collections;
import java.util.List;

public class SignUtil {
	//用于生成签名sign的方法
		public static String createSign(String method, String servicePath, String apiSecret, List<String> paramStrings,
				String postbody) throws UnsupportedEncodingException {
			StringBuffer sb = new StringBuffer(method).append(servicePath);
			Collections.sort(paramStrings);
			sb.append(StringUtils.join(paramStrings, ""));
			if (postbody != null && "POST".equals(method)) {
				sb.append(postbody);
			}
			sb.append(apiSecret);
			String str = URLEncoder.encode(sb.toString(), "UTF-8");
			return getMD5(str);
		}
		//被createSign调用
		private static String getMD5(String str) {
			MessageDigest messageDigest = null;
			byte[] byteArray = null;
			try {
				messageDigest = MessageDigest.getInstance("MD5");
				messageDigest.reset();
				messageDigest.update(str.getBytes("UTF-8"));
				byteArray = messageDigest.digest();
				String byte2hex = byte2hex(byteArray);
				if(StringUtils.isNotBlank(byte2hex)){
					return byte2hex;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
		//被getMD5方法调用
		private static String byte2hex(byte[] data) {
			StringBuffer sb = new StringBuffer();
			int len = data.length;
			for (int i = 0; i < len; i++) {
				String temp = Integer.toHexString(((int) data[i]) & 0xFF);
				for (int t = temp.length(); t < 2; t++) {
					sb.append("0");
				}
				sb.append(temp);
			}
			String s = sb.toString();
			if(StringUtils.isNotBlank(s)){
				return s;
			}
			return null;
		}
		
}
