package com.jeequan.jeepay.thirdparty.channel.yspay.utils;


import java.security.PublicKey;
import java.security.Signature;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class SignUtil {

    private static final String ALGORITHM = "SHA256withRSA";

    /**
     * @Author 胡兴铭
     * @Description 验签
     * @Date 10:38 2020/3/12
     * @Param
     * @return
     */
    public static boolean signVerify(Map<String, Object> map, String signData,PublicKey publicKey)throws Exception {
        byte[] srcData = getSignDataStr(map).getBytes("utf-8");
        return validateSignBySoft(publicKey, org.apache.commons.codec.binary.Base64.decodeBase64(signData), srcData);
    }

    public static boolean validateSignBySoft(PublicKey publicKey,byte[] signData, byte[] srcData) throws Exception {
        Signature st = Signature.getInstance(ALGORITHM);
        st.initVerify(publicKey);
        st.update(srcData);
        return st.verify(signData);
    }

    public static String getSignDataStr(Map<String, Object> map) {
        List<String> keys = new ArrayList<String>(map.keySet());
        Collections.sort(keys);
        StringBuilder sb = new StringBuilder();
        for(String key : keys){
            if("sign".equals(key)) {
                continue;
            }
            sb.append(key).append("=");
            sb.append(map.get(key));
            sb.append("&");
        }
        if(sb.length() > 0) {
            sb.setLength(sb.length() - 1);
        }
        return sb.toString();
    }

    public static String getSignDataStr1(Map<String, String> map) {
        List<String> keys = new ArrayList<String>(map.keySet());
        Collections.sort(keys);
        StringBuilder sb = new StringBuilder();
        for(String key : keys){
            if("sign".equals(key)) {
                continue;
            }
            if("$jacocoData".equals(key)) {
                continue;
            }
            sb.append(key).append("=");
            sb.append(map.get(key));
            sb.append("&");
        }
        if(sb.length() > 0) {
            sb.setLength(sb.length() - 1);
        }
        return sb.toString();
    }
}
