package com.ccwangluo.ccim.util;


import android.util.Log;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * Created by xiang.li on 2015/2/27.
 */
public class HmacUtil {
    private final static String LOG_TAG = HmacUtil.class.getName();
    public static String stringToSign(String appSecret,String data) {
        try {
            Mac mac = Mac.getInstance("hmacSHA256");
            SecretKeySpec secret = new SecretKeySpec(
                    appSecret.getBytes("UTF-8"), mac.getAlgorithm());
            mac.init(secret);
            byte[] bytes = mac.doFinal(data.getBytes());
            return bytesToHex(bytes);
        } catch (NoSuchAlgorithmException e) {
            Log.e(LOG_TAG, "Hash algorithm SHA-1 is not supported", e);
        } catch (UnsupportedEncodingException e) {
            Log.e(LOG_TAG, "Encoding UTF-8 is not supported", e);
        } catch (InvalidKeyException e) {
            Log.e(LOG_TAG, "Invalid key", e);
        }
        return "";
    }


    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if(hex.length() < 2){
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}
