package com.oqpo.api.client.oqlink.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.google.gson.Gson;

public class HmacUtil {

    public static String toHexString(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static String makeHmacValue(String apikey, String secretkey, String body) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secretkey.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        StringBuilder hmac = new StringBuilder();
        hmac.append(apikey);
        hmac.append(":");
        hmac.append(toHexString(sha256_HMAC.doFinal(body.getBytes())));

        return hmac.toString();
    }

    public static String makeHmacValue4OqLink(Object param) throws Exception {
        Gson gson = new Gson();
        String reqJson = gson.toJson(param);
        return makeHmacValue(ApiUserKey.STORE_SCM.getApi_key(), ApiUserKey.STORE_SCM.getSecret_key(), reqJson);
    }

}
