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

package com.nimbusds.jose.crypto.impl;

import com.nimbusds.jose.util.ByteUtils;
import java.security.GeneralSecurityException;
import com.nimbusds.jose.JOSEException;
import com.google.crypto.tink.subtle.XChaCha20Poly1305;
import com.nimbusds.jose.util.Container;
import javax.crypto.SecretKey;
import com.nimbusds.jose.shaded.jcip.ThreadSafe;

@ThreadSafe
public class XC20P
{
    public static final int AUTH_TAG_BIT_LENGTH = 128;
    public static final int IV_BIT_LENGTH = 192;
    
    public static AuthenticatedCipherText encryptAuthenticated(final SecretKey secretKey, final Container<byte[]> ivContainer, final byte[] plainText, final byte[] authData) throws JOSEException {
        XChaCha20Poly1305 aead;
        try {
            aead = new XChaCha20Poly1305(secretKey.getEncoded());
        }
        catch (final GeneralSecurityException e) {
            throw new JOSEException("Invalid XChaCha20Poly1305 key: " + e.getMessage(), e);
        }
        byte[] cipherOutput;
        try {
            cipherOutput = aead.encrypt(plainText, authData);
        }
        catch (final GeneralSecurityException e2) {
            throw new JOSEException("Couldn't encrypt with XChaCha20Poly1305: " + e2.getMessage(), e2);
        }
        final int tagPos = cipherOutput.length - ByteUtils.byteLength(128);
        final int cipherTextPos = ByteUtils.byteLength(192);
        final byte[] iv = ByteUtils.subArray(cipherOutput, 0, cipherTextPos);
        final byte[] cipherText = ByteUtils.subArray(cipherOutput, cipherTextPos, tagPos - cipherTextPos);
        final byte[] authTag = ByteUtils.subArray(cipherOutput, tagPos, ByteUtils.byteLength(128));
        ivContainer.set(iv);
        return new AuthenticatedCipherText(cipherText, authTag);
    }
    
    public static byte[] decryptAuthenticated(final SecretKey secretKey, final byte[] iv, final byte[] cipherText, final byte[] authData, final byte[] authTag) throws JOSEException {
        XChaCha20Poly1305 aead;
        try {
            aead = new XChaCha20Poly1305(secretKey.getEncoded());
        }
        catch (final GeneralSecurityException e) {
            throw new JOSEException("Invalid XChaCha20Poly1305 key: " + e.getMessage(), e);
        }
        final byte[] cipherInput = ByteUtils.concat(new byte[][] { iv, cipherText, authTag });
        try {
            return aead.decrypt(cipherInput, authData);
        }
        catch (final GeneralSecurityException e2) {
            throw new JOSEException("XChaCha20Poly1305 decryption failed: " + e2.getMessage(), e2);
        }
    }
}
