package com.foc.util;

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

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class GlobalUtil {

//    private static GlobalUtil globalUtil;
    private static final String HMAC_SHA1 = "HmacSHA1";
    private static final String ALGORITHM_MD5 = "MD5";
    private GlobalUtil() {
    }

    public static boolean verify(String data, String privateKey, String sign) {
        try {
            String mSign = getParamsSignStr(privateKey, data);
            if(mSign == null || sign == null)
                return false;
            mSign = URLDecoder.decode(mSign, "UTF-8");
            return mSign.equals(sign);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return false;
    }
    public static final String MD5_32bit1(String readyEncryptStr) throws NoSuchAlgorithmException{  
        if(readyEncryptStr != null){  
            //The cipher text converted to hexadecimal string  
            StringBuilder su = new StringBuilder();  
            //Get MD5 digest algorithm's MessageDigest's instance.  
            MessageDigest md = MessageDigest.getInstance(ALGORITHM_MD5);  
            byte [] b = md.digest(readyEncryptStr.getBytes());  
            int temp = 0;  
            //byte array switch hexadecimal number.  
            for(int offset = 0,bLen = b.length; offset < bLen; offset++){  
                temp = b[offset];  
                if(temp < 0){  
                    temp += 256;  
                }  
                int d1 = temp / 16;  
                int d2 = temp % 16;  
                su.append(Integer.toHexString(d1) + Integer.toHexString(d2)) ;  
            }  
            return su.toString();  
        }else{  
            return null;  
        }  
    }  
//    public static GlobalUtil getInstance() {
//        if (globalUtil == null) {
//            globalUtil = new GlobalUtil();
//        }
//        return globalUtil;
//    }

    /**
     * 获取加密后的字符串
     *
     */
    public static String getParamsSignStr(String key, String paramsStr) {
        if (key == null || paramsStr == null) {
            return "";
        }
        try {
            String signedStr = HMACSHA1(key.getBytes("UTF-8"), paramsStr.getBytes("UTF-8"));
            String signedStr1 = base64(signedStr.getBytes("UTF-8"));
            return signedStr1;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 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) throws NoSuchAlgorithmException {
    	
    	//{"shop_code":"ringpu","user_code":"","role_code":"","user_channel":"1002","sub_channel":"AGENCY","version_name":"0.9","password":"111111","telephone":"13752653287"}
        String content = "{\"appCode\":\"30007\",\"appkey\":\"\",\"versionName\":\"6.0.0\",\"platform\":\"Android\",\"deviceToken\":\"deviceToken\",\"language\":\"zh_CN\",email : '123@qwe.com',name : 'name', keywords : '天津', staffAccounts : ['794089036222300160', 'seat791537198252023808']}";
        String sign = GlobalUtil.getParamsSignStr("FvNMhdkN5eTsgAfU2YHGJ2RfpKVi3omn", content);
        String mSign = GlobalUtil.getParamsSignStr("FvNMhdkN5eTsgAfU2YHGJ2RfpKVi3omn", content);
       String ss= HMACSHA1("FvNMhdkN5eTsgAfU2YHGJ2RfpKVi3omn".getBytes(),content.getBytes());
       String md532 = MD5_32bit1(content);  
       System.out.println("前面是否通过："+GlobalUtil.verify(content, "FvNMhdkN5eTsgAfU2YHGJ2RfpKVi3omn", sign));
        System.out.println(md532);
        System.out.println(sign);

//        System.out.println(verify("{appCode:30007}", "FvNMhdkN5eTsgAfU2YHGJ2RfpKVi3omn", "WTRJdjZheXFLdXJ3azFZOWJKelZNaStCajFVPQ=="));
    }

}
