package com.tykj.dev.blockcha.subject.service.impl;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.SortedMap;

/**
 * @author LJJ cnljj1995@gmail.com
 * on 2020-08-18
 */
@Slf4j
class ApiSignatureUtil {

    /**
     * @param map you can use SortedMap<Object, Object> map = new TreeMap<Object, Object>();
     *            need to add nonce,secretID,timestamp(s) columns;
     * @param key SECRET_KEY
     */
    static String getApiSignature(SortedMap<Object, Object> map, String key) {

        StringBuilder sb = new StringBuilder();
        map.forEach((k,v) -> sb.append(k).append("=").append(v).append("&"));
        String str = sb.toString();
        String message = str.substring(0, str.length() - 1);
        return sha256_HMAC(message, key);
    }


    /**
     * 将加密后的字节数组转换成字符串
     *
     * @param b 字节数组
     * @return 字符串
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                hs.append('0');
            }
            hs.append(stmp);
        }
        return hs.toString().toLowerCase();
    }

    /**
     * sha256_HMAC加密
     *
     * @param message 消息
     * @param secret  秘钥
     * @return 加密后字符串
     */
    private static String sha256_HMAC(String message, String secret) {
        String hash = "";
        try {
            Mac sha256 = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
            sha256.init(secretKey);
            byte[] bytes = sha256.doFinal(message.getBytes());
            hash = byteArrayToHexString(bytes);
        } catch (Exception e) {
            log.error("[BlockChain] sha256_HMAC加密出错:{}", e.toString());
        }
        return hash.toUpperCase();
    }


}
