package com.uas.finance.util;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

/**
 * Created by hejq on 2017-11-24.
 */
public class HmacEncoder {
    private final String algorithm;

    public HmacEncoder(String algorithm) {
        this.algorithm = algorithm;
    }

    public byte[] getKey() {
        KeyGenerator keyGenerator = null;

        try {
            keyGenerator = KeyGenerator.getInstance(this.algorithm);
        } catch (NoSuchAlgorithmException var3) {
            throw new RuntimeException(var3.getMessage());
        }

        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey.getEncoded();
    }

    private static Key toKey(byte[] key, String algorithm) {
        return new SecretKeySpec(key, algorithm);
    }

    public byte[] encode(byte[] data, Key key) {
        Mac mac = null;

        try {
            mac = Mac.getInstance(this.algorithm);
            mac.init(key);
        } catch (NoSuchAlgorithmException var5) {
            var5.printStackTrace();
            return new byte[0];
        } catch (InvalidKeyException var6) {
            var6.printStackTrace();
            return new byte[0];
        }

        return mac.doFinal(data);
    }

    public byte[] encode(byte[] data, byte[] key) {
        return this.encode(data, toKey(key, this.algorithm));
    }
}
