package com.winsun.utils;

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

//智能平台5.0加密
public class ZnptSignUtils {
    private static final char[] hexChars = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private static final String MAC_NAME = "HmacSHA1";
    private static final String ENCODING = "UTF-8";
    private static final String macKey = "";
    private final SecretKeySpec secretKey;

    public ZnptSignUtils() {

        try {
            byte[] data = macKey.getBytes(ENCODING);
            this.secretKey = new SecretKeySpec(data, MAC_NAME);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    private String toHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte aByte : bytes) {
            sb.append(hexChars[(aByte >> 4) & 0xF]).append(hexChars[aByte & 0xF]);
        }
        return sb.toString();
    }


    /**
     * @param message
     * @return  生成签名串
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    public String macSHA1(String message) throws
            UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        Mac mac = Mac.getInstance(MAC_NAME);
        mac.init(secretKey);
        byte[] text = message.getBytes(ENCODING);
        return "sha1=" + toHex(mac.doFinal(text));
    }


}