package com.alterdekim.game.crypto;

import lombok.extern.slf4j.Slf4j;

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

@Slf4j
public class HMAC {
    private Mac hmacSHA256;

    public HMAC() {
        try {
            this.hmacSHA256 = Mac.getInstance("HmacSHA256");
        } catch (SecurityException e) {
            log.error("Security exception when getting HMAC", e);
        } catch (NoSuchAlgorithmException e) {
            log.error("HMAC SHA256 does not exist");
        }
    }

    public byte[] calculateHmacSHA256(byte[] input, byte[] key, int length) {
        byte[] output = null;
        try {
            hmacSHA256.init(new SecretKeySpec(key, 0, length, "HmacSHA256"));
            output = hmacSHA256.doFinal(input);
        } catch (InvalidKeyException e) {
            log.error("Invalid key", e);
        }
        return output;
    }
}
