package org.bouncycastle.openpgp.operator.jcajce;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.bcpg.AEADEncDataPacket;
import org.bouncycastle.bcpg.AEADUtils;
import org.bouncycastle.bcpg.SymmetricEncIntegrityPacket;
import org.bouncycastle.bcpg.SymmetricKeyUtils;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.generators.HKDFBytesGenerator;
import org.bouncycastle.crypto.params.HKDFParameters;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPSessionKey;
import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.openpgp.operator.PGPDataDecryptor;
import org.bouncycastle.openpgp.operator.PGPDigestCalculator;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Exceptions;
import org.bouncycastle.util.Pack;
import org.bouncycastle.util.io.Streams;

/* JADX INFO: loaded from: classes2.dex */
class JceAEADUtil {
    private final OperatorHelper helper;

    /* JADX INFO: loaded from: classes.dex */
    static class PGPAeadInputStream extends InputStream {
        private final byte[] aaData;
        private final int aeadTagLength;
        private final byte[] buf;
        private final Cipher c;
        private final int chunkLength;
        private byte[] data;
        private int dataOff;
        private final InputStream in;
        private final byte[] iv;
        private final SecretKey secretKey;
        private boolean v5StyleAEAD;
        private long chunkIndex = 0;
        private long totalBytes = 0;

        public PGPAeadInputStream(boolean z, InputStream inputStream, Cipher cipher, SecretKey secretKey, byte[] bArr, int i, int i2, int i3, byte[] bArr2) throws IOException {
            this.v5StyleAEAD = z;
            this.in = inputStream;
            this.iv = bArr;
            this.chunkLength = (int) JceAEADUtil.getChunkLength(i3);
            this.aeadTagLength = AEADUtils.getAuthTagLength(i2);
            this.buf = new byte[this.chunkLength + this.aeadTagLength + this.aeadTagLength];
            this.c = cipher;
            this.secretKey = secretKey;
            this.aaData = bArr2;
            Streams.readFully(inputStream, this.buf, 0, this.aeadTagLength + this.aeadTagLength);
            this.data = readBlock();
            this.dataOff = 0;
        }

        private byte[] readBlock() throws IOException {
            int fully = Streams.readFully(this.in, this.buf, this.aeadTagLength + this.aeadTagLength, this.chunkLength);
            if (fully == 0) {
                return null;
            }
            byte[] bArr = new byte[this.v5StyleAEAD ? 13 : this.aaData.length];
            System.arraycopy(this.aaData, 0, bArr, 0, this.aaData.length);
            if (this.v5StyleAEAD) {
                JceAEADUtil.xorChunkId(bArr, this.chunkIndex);
            }
            try {
                JceAEADCipherUtil.setUpAeadCipher(this.c, this.secretKey, 2, JceAEADUtil.getNonce(this.iv, this.chunkIndex), 128, bArr);
                byte[] bArrDoFinal = this.c.doFinal(this.buf, 0, this.aeadTagLength + fully);
                this.totalBytes += (long) bArrDoFinal.length;
                this.chunkIndex++;
                System.arraycopy(this.buf, this.aeadTagLength + fully, this.buf, 0, this.aeadTagLength);
                if (fully != this.chunkLength) {
                    byte[] adata = PGPAeadOutputStream.getAdata(this.v5StyleAEAD, this.aaData, this.chunkIndex, this.totalBytes);
                    try {
                        boolean z = this.v5StyleAEAD;
                        Cipher cipher = this.c;
                        if (z) {
                            JceAEADCipherUtil.setUpAeadCipher(cipher, this.secretKey, 2, JceAEADUtil.getNonce(this.iv, this.chunkIndex), 128, Arrays.concatenate(adata, Pack.longToBigEndian(this.totalBytes)));
                        } else {
                            JceAEADCipherUtil.setUpAeadCipher(cipher, this.secretKey, 2, JceAEADUtil.getNonce(this.iv, this.chunkIndex), 128, adata);
                        }
                        this.c.doFinal(this.buf, 0, this.aeadTagLength);
                    } catch (GeneralSecurityException e) {
                        throw new IOException("exception processing final tag: " + e.getMessage());
                    }
                } else {
                    Streams.readFully(this.in, this.buf, this.aeadTagLength, this.aeadTagLength);
                }
                return bArrDoFinal;
            } catch (GeneralSecurityException e2) {
                throw new IOException("exception processing chunk " + this.chunkIndex + ": " + e2.getMessage());
            }
        }

        @Override // java.io.InputStream
        public int available() throws IOException {
            if (this.data != null && this.dataOff == this.data.length) {
                this.data = readBlock();
                this.dataOff = 0;
            }
            if (this.data == null) {
                return -1;
            }
            return this.data.length - this.dataOff;
        }

        @Override // java.io.InputStream
        public int read() throws IOException {
            if (this.data != null && this.dataOff == this.data.length) {
                this.data = readBlock();
                this.dataOff = 0;
            }
            if (this.data == null) {
                return -1;
            }
            byte[] bArr = this.data;
            int i = this.dataOff;
            this.dataOff = i + 1;
            return bArr[i] & 255;
        }

        @Override // java.io.InputStream
        public int read(byte[] bArr, int i, int i2) throws IOException {
            if (this.data != null && this.dataOff == this.data.length) {
                this.data = readBlock();
                this.dataOff = 0;
            }
            if (this.data == null) {
                return -1;
            }
            int iMin = Math.min(i2, available());
            System.arraycopy(this.data, this.dataOff, bArr, i, iMin);
            this.dataOff += iMin;
            return iMin;
        }

        @Override // java.io.InputStream
        public long skip(long j) throws IOException {
            if (j <= 0) {
                return 0L;
            }
            int iMin = (int) Math.min(j, available());
            this.dataOff += iMin;
            return iMin;
        }
    }

    /* JADX INFO: loaded from: classes.dex */
    static class PGPAeadOutputStream extends OutputStream {
        private final byte[] aaData;
        private final Cipher c;
        private final int chunkLength;
        private final byte[] data;
        private int dataOff;
        private final boolean isV5AEAD;
        private final byte[] iv;
        private final OutputStream out;
        private final SecretKey secretKey;
        private long chunkIndex = 0;
        private long totalBytes = 0;

        public PGPAeadOutputStream(boolean z, OutputStream outputStream, Cipher cipher, SecretKey secretKey, byte[] bArr, int i, int i2, int i3) {
            this.isV5AEAD = z;
            this.out = outputStream;
            this.iv = bArr;
            this.chunkLength = (int) JceAEADUtil.getChunkLength(i3);
            this.data = new byte[this.chunkLength];
            this.c = cipher;
            this.secretKey = secretKey;
            this.aaData = createAAD(z, i, i2, i3);
        }

        private byte[] createAAD(boolean z, int i, int i2, int i3) {
            return z ? AEADEncDataPacket.createAAData(1, i, i2, i3) : SymmetricEncIntegrityPacket.createAAData(2, i, i2, i3);
        }

        private void finish() throws IOException {
            if (this.dataOff > 0) {
                writeBlock();
            }
            byte[] adata = getAdata(this.isV5AEAD, this.aaData, this.chunkIndex, this.totalBytes);
            try {
                boolean z = this.isV5AEAD;
                Cipher cipher = this.c;
                if (z) {
                    JceAEADCipherUtil.setUpAeadCipher(cipher, this.secretKey, 1, JceAEADUtil.getNonce(this.iv, this.chunkIndex), 128, Arrays.concatenate(adata, Pack.longToBigEndian(this.totalBytes)));
                } else {
                    JceAEADCipherUtil.setUpAeadCipher(cipher, this.secretKey, 1, JceAEADUtil.getNonce(this.iv, this.chunkIndex), 128, adata);
                }
                this.out.write(this.c.doFinal(this.aaData, 0, 0));
                this.out.close();
            } catch (GeneralSecurityException e) {
                throw new IOException("exception processing final tag: " + e.getMessage());
            }
        }

        /* JADX INFO: Access modifiers changed from: private */
        public static byte[] getAdata(boolean z, byte[] bArr, long j, long j2) {
            if (z) {
                byte[] bArr2 = new byte[13];
                System.arraycopy(bArr, 0, bArr2, 0, bArr.length);
                JceAEADUtil.xorChunkId(bArr2, j);
                return bArr2;
            }
            byte[] bArr3 = new byte[bArr.length + 8];
            System.arraycopy(bArr, 0, bArr3, 0, bArr.length);
            System.arraycopy(Pack.longToBigEndian(j2), 0, bArr3, bArr.length, 8);
            return bArr3;
        }

        private void writeBlock() throws IOException {
            byte[] bArr = new byte[this.isV5AEAD ? 13 : this.aaData.length];
            System.arraycopy(this.aaData, 0, bArr, 0, this.aaData.length);
            if (this.isV5AEAD) {
                JceAEADUtil.xorChunkId(bArr, this.chunkIndex);
            }
            try {
                JceAEADCipherUtil.setUpAeadCipher(this.c, this.secretKey, 1, JceAEADUtil.getNonce(this.iv, this.chunkIndex), 128, bArr);
                this.out.write(this.c.doFinal(this.data, 0, this.dataOff));
                this.totalBytes += (long) this.dataOff;
                this.chunkIndex++;
                this.dataOff = 0;
            } catch (GeneralSecurityException e) {
                throw new IOException("exception processing chunk " + this.chunkIndex + ": " + e.getMessage());
            }
        }

        @Override // java.io.OutputStream, java.io.Closeable, java.lang.AutoCloseable
        public void close() throws IOException {
            finish();
        }

        @Override // java.io.OutputStream
        public void write(int i) throws IOException {
            if (this.dataOff == this.data.length) {
                writeBlock();
            }
            byte[] bArr = this.data;
            int i2 = this.dataOff;
            this.dataOff = i2 + 1;
            bArr[i2] = (byte) i;
        }

        @Override // java.io.OutputStream
        public void write(byte[] bArr, int i, int i2) throws IOException {
            if (this.dataOff == this.data.length) {
                writeBlock();
            }
            int length = this.data.length - this.dataOff;
            byte[] bArr2 = this.data;
            if (i2 < length) {
                System.arraycopy(bArr, i, bArr2, this.dataOff, i2);
                this.dataOff += i2;
                return;
            }
            int length2 = bArr2.length - this.dataOff;
            System.arraycopy(bArr, i, this.data, this.dataOff, length2);
            this.dataOff += length2;
            writeBlock();
            int length3 = i2 - length2;
            while (true) {
                i += length2;
                if (length3 < this.data.length) {
                    break;
                }
                System.arraycopy(bArr, i, this.data, 0, this.data.length);
                this.dataOff = this.data.length;
                writeBlock();
                length3 -= this.data.length;
                length2 = this.data.length;
            }
            if (length3 > 0) {
                System.arraycopy(bArr, i, this.data, 0, length3);
                this.dataOff = length3;
            }
        }
    }

    public JceAEADUtil(OperatorHelper operatorHelper) {
        this.helper = operatorHelper;
    }

    static byte[][] deriveMessageKeyAndIv(int i, int i2, byte[] bArr, byte[] bArr2, byte[] bArr3) throws PGPException {
        int keyLengthInOctets = SymmetricKeyUtils.getKeyLengthInOctets(i2);
        int iVLength = AEADUtils.getIVLength(i) + keyLengthInOctets;
        byte[] bArrGenerateHKDFBytes = generateHKDFBytes(bArr, bArr2, bArr3, iVLength - 8);
        return new byte[][]{Arrays.copyOfRange(bArrGenerateHKDFBytes, 0, keyLengthInOctets), Arrays.copyOfRange(bArrGenerateHKDFBytes, keyLengthInOctets, iVLength)};
    }

    static byte[] generateHKDFBytes(byte[] bArr, byte[] bArr2, byte[] bArr3, int i) {
        HKDFParameters hKDFParameters = new HKDFParameters(bArr, bArr2, bArr3);
        HKDFBytesGenerator hKDFBytesGenerator = new HKDFBytesGenerator(new SHA256Digest());
        hKDFBytesGenerator.init(hKDFParameters);
        byte[] bArr4 = new byte[i];
        hKDFBytesGenerator.generateBytes(bArr4, 0, i);
        return bArr4;
    }

    protected static long getChunkLength(int i) {
        return 1 << (i + 6);
    }

    protected static byte[] getNonce(byte[] bArr, long j) throws CloneNotSupportedException {
        byte[] bArrClone = Arrays.clone(bArr);
        xorChunkId(bArrClone, j);
        return bArrClone;
    }

    static byte[] processAeadKeyData(JceAEADUtil jceAEADUtil, int i, int i2, int i3, byte[] bArr, byte[] bArr2, int i4, int i5, byte[] bArr3, int i6, int i7, byte[] bArr4) throws PGPException {
        byte b = (byte) (i4 | 192);
        byte[] bArrGenerateHKDFBytes = generateHKDFBytes(bArr, null, new byte[]{b, (byte) i5, (byte) i2, (byte) i3}, SymmetricKeyUtils.getKeyLengthInOctets(i2));
        try {
            byte[] bArrPrepend = Arrays.prepend(bArr4, b);
            SecretKeySpec secretKeySpec = new SecretKeySpec(bArrGenerateHKDFBytes, PGPUtil.getSymmetricCipherName(i2));
            Cipher cipherCreateAEADCipher = jceAEADUtil.createAEADCipher(i2, i3);
            JceAEADCipherUtil.setUpAeadCipher(cipherCreateAEADCipher, secretKeySpec, i, bArr2, 128, bArrPrepend);
            return cipherCreateAEADCipher.doFinal(bArr3, i6, i7);
        } catch (GeneralSecurityException e) {
            throw new PGPException("Exception recovering AEAD protected private key material", e);
        }
    }

    protected static void xorChunkId(byte[] bArr, long j) {
        int length = bArr.length - 8;
        int i = length + 1;
        bArr[length] = (byte) (bArr[length] ^ ((byte) (j >> 56)));
        int i2 = i + 1;
        bArr[i] = (byte) (bArr[i] ^ ((byte) (j >> 48)));
        int i3 = i2 + 1;
        bArr[i2] = (byte) (bArr[i2] ^ ((byte) (j >> 40)));
        int i4 = i3 + 1;
        bArr[i3] = (byte) (bArr[i3] ^ ((byte) (j >> 32)));
        int i5 = i4 + 1;
        bArr[i4] = (byte) (bArr[i4] ^ ((byte) (j >> 24)));
        int i6 = i5 + 1;
        bArr[i5] = (byte) (bArr[i5] ^ ((byte) (j >> 16)));
        int i7 = i6 + 1;
        bArr[i6] = (byte) (((byte) (j >> 8)) ^ bArr[i6]);
        bArr[i7] = (byte) (((byte) j) ^ bArr[i7]);
    }

    Cipher createAEADCipher(int i, int i2) throws PGPException {
        String str;
        if (i != 7 && i != 8 && i != 9 && i != 11 && i != 12 && i != 13) {
            throw new PGPException("AEAD only supported for AES and Camellia based algorithms");
        }
        switch (i2) {
            case 1:
                str = "EAX";
                break;
            case 2:
                str = "OCB";
                break;
            case 3:
                str = "GCM";
                break;
            default:
                throw new PGPException("encountered unknown AEAD algorithm: " + i2);
        }
        return this.helper.createCipher(PGPUtil.getSymmetricCipherName(i) + "/" + str + "/NoPadding");
    }

    PGPDataDecryptor createOpenPgpV5DataDecryptor(AEADEncDataPacket aEADEncDataPacket, PGPSessionKey pGPSessionKey) throws PGPException {
        final byte aEADAlgorithm = aEADEncDataPacket.getAEADAlgorithm();
        final byte[] iv = aEADEncDataPacket.getIV();
        final int chunkSize = aEADEncDataPacket.getChunkSize();
        final int algorithm = pGPSessionKey.getAlgorithm();
        byte[] key = pGPSessionKey.getKey();
        final byte[] aAData = aEADEncDataPacket.getAAData();
        try {
            final SecretKeySpec secretKeySpec = new SecretKeySpec(key, PGPUtil.getSymmetricCipherName(algorithm));
            final Cipher cipherCreateAEADCipher = createAEADCipher(algorithm, aEADAlgorithm);
            return new PGPDataDecryptor(this) { // from class: org.bouncycastle.openpgp.operator.jcajce.JceAEADUtil.1
                final /* synthetic */ JceAEADUtil this$0;

                {
                    this.this$0 = this;
                }

                @Override // org.bouncycastle.openpgp.operator.PGPDataDecryptor
                public int getBlockSize() {
                    return cipherCreateAEADCipher.getBlockSize();
                }

                @Override // org.bouncycastle.openpgp.operator.PGPDataDecryptor
                public InputStream getInputStream(InputStream inputStream) {
                    try {
                        return new PGPAeadInputStream(true, inputStream, cipherCreateAEADCipher, secretKeySpec, iv, algorithm, aEADAlgorithm, chunkSize, aAData);
                    } catch (IOException e) {
                        throw Exceptions.illegalStateException("unable to open stream: " + e.getMessage(), e);
                    }
                }

                @Override // org.bouncycastle.openpgp.operator.PGPDataDecryptor
                public PGPDigestCalculator getIntegrityCalculator() {
                    return new SHA1PGPDigestCalculator();
                }
            };
        } catch (PGPException e) {
            throw e;
        } catch (Exception e2) {
            throw new PGPException("Exception creating cipher", e2);
        }
    }

    PGPDataDecryptor createOpenPgpV6DataDecryptor(SymmetricEncIntegrityPacket symmetricEncIntegrityPacket, PGPSessionKey pGPSessionKey) throws PGPException {
        final int cipherAlgorithm = symmetricEncIntegrityPacket.getCipherAlgorithm();
        final int aeadAlgorithm = symmetricEncIntegrityPacket.getAeadAlgorithm();
        final int chunkSize = symmetricEncIntegrityPacket.getChunkSize();
        byte[] salt = symmetricEncIntegrityPacket.getSalt();
        final byte[] aAData = symmetricEncIntegrityPacket.getAAData();
        byte[][] bArrDeriveMessageKeyAndIv = deriveMessageKeyAndIv(aeadAlgorithm, cipherAlgorithm, pGPSessionKey.getKey(), salt, aAData);
        byte[] bArr = bArrDeriveMessageKeyAndIv[0];
        final byte[] bArr2 = bArrDeriveMessageKeyAndIv[1];
        try {
            final SecretKeySpec secretKeySpec = new SecretKeySpec(bArr, PGPUtil.getSymmetricCipherName(cipherAlgorithm));
            final Cipher cipherCreateAEADCipher = createAEADCipher(cipherAlgorithm, aeadAlgorithm);
            return new PGPDataDecryptor(this) { // from class: org.bouncycastle.openpgp.operator.jcajce.JceAEADUtil.2
                final /* synthetic */ JceAEADUtil this$0;

                {
                    this.this$0 = this;
                }

                @Override // org.bouncycastle.openpgp.operator.PGPDataDecryptor
                public int getBlockSize() {
                    return cipherCreateAEADCipher.getBlockSize();
                }

                @Override // org.bouncycastle.openpgp.operator.PGPDataDecryptor
                public InputStream getInputStream(InputStream inputStream) {
                    try {
                        return new PGPAeadInputStream(false, inputStream, cipherCreateAEADCipher, secretKeySpec, bArr2, cipherAlgorithm, aeadAlgorithm, chunkSize, aAData);
                    } catch (IOException e) {
                        throw Exceptions.illegalStateException("unable to open stream: " + e.getMessage(), e);
                    }
                }

                @Override // org.bouncycastle.openpgp.operator.PGPDataDecryptor
                public PGPDigestCalculator getIntegrityCalculator() {
                    return new SHA1PGPDigestCalculator();
                }
            };
        } catch (PGPException e) {
            throw e;
        } catch (Exception e2) {
            throw new PGPException("Exception creating cipher", e2);
        }
    }
}
