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

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

import java.util.Arrays;
import java.security.GeneralSecurityException;
import com.google.crypto.tink.aead.internal.InsecureNonceChaCha20Poly1305;
import com.google.crypto.tink.aead.internal.InsecureNonceChaCha20Poly1305Jce;
import java.security.InvalidAlgorithmParameterException;
import com.google.errorprone.annotations.Immutable;

@Immutable
final class ChaCha20Poly1305HpkeAead implements HpkeAead
{
    @Override
    public byte[] seal(final byte[] key, final byte[] nonce, final byte[] plaintext, final int ciphertextOffset, final byte[] associatedData) throws GeneralSecurityException {
        if (key.length != this.getKeyLength()) {
            throw new InvalidAlgorithmParameterException("Unexpected key length: " + this.getKeyLength());
        }
        if (InsecureNonceChaCha20Poly1305Jce.isSupported()) {
            final InsecureNonceChaCha20Poly1305Jce aead = InsecureNonceChaCha20Poly1305Jce.create(key);
            return aead.encrypt(nonce, plaintext, ciphertextOffset, associatedData);
        }
        final InsecureNonceChaCha20Poly1305 aead2 = new InsecureNonceChaCha20Poly1305(key);
        final byte[] aeadCiphertext = aead2.encrypt();
        if (aeadCiphertext.length > Integer.MAX_VALUE - ciphertextOffset) {
            throw new InvalidAlgorithmParameterException("Plaintext too long");
        }
        final byte[] ciphertext = new byte[ciphertextOffset + aeadCiphertext.length];
        System.arraycopy(aeadCiphertext, 0, ciphertext, ciphertextOffset, aeadCiphertext.length);
        return ciphertext;
    }
    
    @Override
    public byte[] open(final byte[] key, final byte[] nonce, final byte[] ciphertext, final int ciphertextOffset, final byte[] associatedData) throws GeneralSecurityException {
        if (key.length != this.getKeyLength()) {
            throw new InvalidAlgorithmParameterException("Unexpected key length: " + this.getKeyLength());
        }
        if (InsecureNonceChaCha20Poly1305Jce.isSupported()) {
            final InsecureNonceChaCha20Poly1305Jce aead = InsecureNonceChaCha20Poly1305Jce.create(key);
            return aead.decrypt(nonce, ciphertext, ciphertextOffset, associatedData);
        }
        final byte[] aeadCiphertext = Arrays.copyOfRange(ciphertext, ciphertextOffset, ciphertext.length);
        final InsecureNonceChaCha20Poly1305 aead2 = new InsecureNonceChaCha20Poly1305(key);
        return aead2.decrypt();
    }
    
    @Override
    public byte[] getAeadId() {
        return HpkeUtil.CHACHA20_POLY1305_AEAD_ID;
    }
    
    @Override
    public int getKeyLength() {
        return 32;
    }
    
    @Override
    public int getNonceLength() {
        return 12;
    }
}
