// 
// Decompiled by Procyon v0.6.0
// 

package com.google.crypto.tink.mac.internal;

import com.google.crypto.tink.subtle.Bytes;
import java.util.Arrays;
import com.google.crypto.tink.mac.HmacParameters;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.Key;
import javax.crypto.spec.SecretKeySpec;
import com.google.crypto.tink.InsecureSecretKeyAccess;
import com.google.crypto.tink.subtle.EngineFactory;
import com.google.crypto.tink.mac.HmacKey;
import javax.crypto.Mac;
import com.google.crypto.tink.AccessesPartialKey;
import com.google.crypto.tink.mac.ChunkedMacComputation;

@AccessesPartialKey
final class ChunkedHmacComputation implements ChunkedMacComputation
{
    private static final byte[] formatVersion;
    private final Mac mac;
    private final HmacKey key;
    private boolean finalized;
    
    ChunkedHmacComputation(final HmacKey key) throws GeneralSecurityException {
        this.finalized = false;
        (this.mac = EngineFactory.MAC.getInstance(composeAlgorithmName(key))).init(new SecretKeySpec(key.getKeyBytes().toByteArray(InsecureSecretKeyAccess.get()), "HMAC"));
        this.key = key;
    }
    
    @Override
    public void update(final ByteBuffer data) {
        if (this.finalized) {
            throw new IllegalStateException("Cannot update after computing the MAC tag. Please create a new object.");
        }
        this.mac.update(data);
    }
    
    @Override
    public byte[] computeMac() throws GeneralSecurityException {
        if (this.finalized) {
            throw new IllegalStateException("Cannot compute after already computing the MAC tag. Please create a new object.");
        }
        if (this.key.getParameters().getVariant() == HmacParameters.Variant.LEGACY) {
            this.update(ByteBuffer.wrap(ChunkedHmacComputation.formatVersion));
        }
        this.finalized = true;
        return Bytes.concat(new byte[][] { this.key.getOutputPrefix().toByteArray(), Arrays.copyOf(this.mac.doFinal(), this.key.getParameters().getCryptographicTagSizeBytes()) });
    }
    
    private static String composeAlgorithmName(final HmacKey key) {
        return "HMAC" + key.getParameters().getHashType();
    }
    
    static {
        formatVersion = new byte[] { 0 };
    }
}
