package com.bcxin.utils.wps;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.HmacUtils;

import java.util.*;

import static org.apache.commons.codec.binary.Base64.encodeBase64String;

/**
 * @author jianjun.wang
 * @version V1.0
 * @className WpsSignatureUtils
 * @packageName com.bcxin.utils.wps
 * @description 签名方法
 * @data 2019-09-02 13:54
 **/
public class WpsSignatureUtils {

    public static String getSignature(Map<String, String> params, String appId, String appSecret) {
        List<String> keys = new ArrayList();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            keys.add(entry.getKey());
        }

        // 将所有参数按key的升序排序
        Collections.sort(keys, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });

        // 构造签名的源字符串
        StringBuilder contents = new StringBuilder("");
        for (String key : keys) {

            if (key == "_w_signature") {
                continue;
            }
            contents.append(key + "=").append(params.get(key));
//            System.out.println("key:" + key + ",value:" + params.get(key));
        }
        contents.append("_w_secretkey=").append(appSecret);


//        System.out.println(appSecret);
//        System.out.println(contents.toString());

        // 进行hmac sha1 签名
        byte[] bytes = HmacUtils.
                hmacSha1(appSecret.getBytes(), contents.toString().getBytes());

        //字符串经过Base64编码
        String sign = encodeBase64String(bytes);
//        System.out.println(sign);
        return sign;
    }

    public static Map<String, String> paramToMap(String paramStr) {
        String[] params = paramStr.split("&");
        Map<String, String> resMap = new HashMap<String, String>();
        for (int i = 0; i < params.length; i++) {
            String[] param = params[i].split("=");
            if (param.length >= 2) {
                String key = param[0];
                String value = param[1];
                for (int j = 2; j < param.length; j++) {
                    value += "=" + param[j];
                }
                resMap.put(key, value);
            }
        }
        return resMap;
    }


}
