package cn.freemud.utils;

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


public class HMacSHA256 {


    /**
     * HMacSHA256 类型签名
     * @param message 签名字符串
     * @param secret 私钥
     * @return 加密后字符串
     */
    private static String encrypt(String message, String secret) {
        String hash = "";
        try {
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
            hash = byteArrayToHexString(bytes);
//            System.out.println(hash);
        } catch (Exception e) {
            System.out.println("Error HmacSHA256 ===========" + e.getMessage());
        }
        return hash;
    }

    /**
     * 将加密后的字节数组转化成字符串
     * @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();
    }

    String buildMessage(String apply_mchid, String sign_mchid, String store_id) {
        return "apply_mchid="+apply_mchid+"&sign_mchid="+sign_mchid+"&store_id="+store_id;
    }

}
