package com.fos.core.utils;

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

public class GlobalUtil {

    private static GlobalUtil globalUtil;
    private static final String HMAC_SHA1 = "HmacSHA1";

    private GlobalUtil() {
    }

    public static GlobalUtil getInstance() {
        if (globalUtil == null) {
            globalUtil = new GlobalUtil();
        }
        return globalUtil;
    }

    /**
     * 获取加密后的字符串
     * 
     * @param key
     *            加密需要的key
     * @param params
     *            要加密的请求参数
     * @return
     */
    public static String getParamsSignStr(String key, String paramsStr) {

        if (key == null || paramsStr == null) {
            return "";
        }

        String signedStr = HMACSHA1(key.getBytes(), paramsStr.getBytes());
        String signedStr1 = base64(signedStr.getBytes());

        return signedStr1;
    }

    /**
     * HMACSHA1加密
     * 
     * @param key
     *            加密使用的key
     * @param strByte
     *            待加密的数据
     * @return 生成MD5编码的字符串
     */

    public static String HMACSHA1(byte[] key, byte[] strByte) {

        byte[] rawHmac = null;
        try {
            SecretKeySpec signingKey = new SecretKeySpec(key, HMAC_SHA1);
            Mac mac = Mac.getInstance(HMAC_SHA1);

            mac.init(signingKey);
            rawHmac = mac.doFinal(strByte);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return base64(rawHmac);
    }

    /**
     * base64加密
     */
    public static String base64(byte[] val) {
        if (val == null)
            return null;
        else
            return Base64.encode(val);
    }

    public static void main(String[] args) {
    	
    	//{"shop_code":"ringpu","user_code":"","role_code":"","user_channel":"1002","sub_channel":"AGENCY","version_name":"0.9","password":"111111","telephone":"13752653287"}
        String param = "{\"shop_code\":\"ringpu\",\"role_code\":\"_USER\",\"user_channel\":\"1001\",\"version_name\":\"1.0\",\"user_code\":\"zpqbcrotxoadvopnalitndt7nhtfafis,\"}";
        String afterEncode = "WmZBVE9xUWFseWNJREF2MjJqaVV4NW1MMFh3PQ==";
        String check = getParamsSignStr("FvNMhdkN5eTsgAfU2YHGJ2RfpKVi3omn", param);
        System.out.println(check);
        System.out.println(afterEncode);
    }

}
