package com.ejweb.core.security;

import com.ejweb.conf.GConstants;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder;

/**
 * Created by owner on 2017/4/8.
 */
public class SignUtil {
    private static final String HMAC_SHA1 = "HmacSHA1";
    private static final String SIGN_PRIVATE_KEY        = GConstants.getValue("content.sign.private.key", "FvNMhdkN5eTsgAfU2YHGJ2RfpKVi3omn");// 签名私钥

    /**
     *
     * @param data
     * @param sign
     * @return
     */
    public static boolean verify(String data, String sign) {

        return  SignUtil.verify(data, SIGN_PRIVATE_KEY, sign);
    }
    public static boolean verify(String data, String privateKey, String sign) {
        try {
            String mSign = sign(privateKey, data);
            if(mSign == null || sign == null)
                return true;
            mSign = URLDecoder.decode(mSign, "UTF-8");
            return mSign.equals(sign);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return false;
    }
    public static String sign(String data) {

        return  SignUtil.sign(SIGN_PRIVATE_KEY, data);
    }
    public static String sign(String privateKey, String data) {
        try {
            byte[] keyBytes  = privateKey.getBytes("UTF-8");
            byte[] dataBytes = data.getBytes("UTF-8");
            SecretKeySpec signingKey = new SecretKeySpec(keyBytes, HMAC_SHA1);
            Mac mac = Mac.getInstance(HMAC_SHA1);
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(dataBytes);
            String signedStr  = Base64Util.byteArrayToBase64(rawHmac);
            String signedStr1 = Base64Util.byteArrayToBase64(signedStr.getBytes("UTF-8"));
            return signedStr1;
        } catch (Exception e) {
            // TODO: handle exception
        }
        return "";
    }
    public static void main(String[] args) {

        String param = "{\"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  = SignUtil.sign(param);
        System.out.println(SignUtil.verify(param, "WWNlY0MwZ1A1L0VQbElDOHI2VkJSbDZ1YzlFPQ=="));
        System.out.println(sign);
    }
}
