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

package com.google.crypto.tink.subtle;

import java.util.Arrays;
import java.security.GeneralSecurityException;
import java.nio.ByteBuffer;
import java.security.InvalidKeyException;
import com.google.crypto.tink.aead.internal.InsecureNonceChaCha20;

class ChaCha20 implements IndCpaCipher
{
    static final int NONCE_LENGTH_IN_BYTES = 12;
    private final InsecureNonceChaCha20 cipher;
    
    ChaCha20(final byte[] key, final int initialCounter) throws InvalidKeyException {
        this.cipher = new InsecureNonceChaCha20(key, initialCounter);
    }
    
    @Override
    public byte[] encrypt(final byte[] plaintext) throws GeneralSecurityException {
        final ByteBuffer output = ByteBuffer.allocate(12 + plaintext.length);
        final byte[] nonce = Random.randBytes(12);
        output.put(nonce);
        this.cipher.encrypt();
        return output.array();
    }
    
    @Override
    public byte[] decrypt(final byte[] ciphertext) throws GeneralSecurityException {
        if (ciphertext.length < 12) {
            throw new GeneralSecurityException("ciphertext too short");
        }
        final byte[] nonce = Arrays.copyOf(ciphertext, 12);
        final ByteBuffer rawCiphertext = ByteBuffer.wrap(ciphertext, 12, ciphertext.length - 12);
        return this.cipher.decrypt();
    }
}
