package org.bouncycastle.openpgp.operator.bc;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.bouncycastle.bcpg.AEADEncDataPacket;
import org.bouncycastle.bcpg.AEADUtils;
import org.bouncycastle.bcpg.SymmetricEncIntegrityPacket;
import org.bouncycastle.bcpg.SymmetricKeyUtils;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.engines.CamelliaEngine;
import org.bouncycastle.crypto.generators.HKDFBytesGenerator;
import org.bouncycastle.crypto.modes.AEADBlockCipher;
import org.bouncycastle.crypto.modes.EAXBlockCipher;
import org.bouncycastle.crypto.modes.GCMBlockCipher;
import org.bouncycastle.crypto.modes.OCBBlockCipher;
import org.bouncycastle.crypto.params.AEADParameters;
import org.bouncycastle.crypto.params.HKDFParameters;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPSessionKey;
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: classes3.dex */
public class BcAEADUtil {
    static final String GetEskAndTagErrorMessage = "cannot encrypt session info";
    private static final String ProcessAeadKeyDataErrorMessage = "Exception recovering AEAD protected private key material";
    static final String RecoverAEADEncryptedSessionDataErrorMessage = "Exception recovering session info";

    /* JADX INFO: loaded from: classes2.dex */
    private interface Engine {
        BlockCipher newInstance();
    }

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

        public PGPAeadInputStream(boolean z, InputStream inputStream, AEADBlockCipher aEADBlockCipher, KeyParameter keyParameter, byte[] bArr, int i, int i2, int i3, byte[] bArr2) throws IOException {
            this.isV5StyleAEAD = z;
            this.in = inputStream;
            this.iv = bArr;
            this.chunkLength = (int) BcAEADUtil.getChunkLength(i3);
            this.tagLen = AEADUtils.getAuthTagLength(i2);
            this.buf = new byte[this.chunkLength + this.tagLen + this.tagLen];
            this.c = aEADBlockCipher;
            this.secretKey = keyParameter;
            this.aaData = bArr2;
            Streams.readFully(inputStream, this.buf, 0, this.tagLen + this.tagLen);
            this.data = readBlock();
            this.dataOff = 0;
        }

        /* 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);
                BcAEADUtil.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 byte[] readBlock() throws IOException {
            int fully = Streams.readFully(this.in, this.buf, this.tagLen + this.tagLen, this.chunkLength);
            if (fully == 0) {
                return null;
            }
            byte[] bArr = new byte[this.isV5StyleAEAD ? 13 : this.aaData.length];
            System.arraycopy(this.aaData, 0, bArr, 0, this.aaData.length);
            if (this.isV5StyleAEAD) {
                BcAEADUtil.xorChunkId(bArr, this.chunkIndex);
            }
            try {
                byte[] bArrProcessAEADData = BcAEADUtil.processAEADData(false, this.c, this.secretKey, BcAEADUtil.getNonce(this.iv, this.chunkIndex), bArr, this.buf, 0, fully + this.tagLen);
                this.totalBytes += (long) bArrProcessAEADData.length;
                this.chunkIndex++;
                System.arraycopy(this.buf, this.tagLen + fully, this.buf, 0, this.tagLen);
                if (fully != this.chunkLength) {
                    try {
                        this.c.init(false, new AEADParameters(this.secretKey, 128, BcAEADUtil.getNonce(this.iv, this.chunkIndex), getAdata(this.isV5StyleAEAD, this.aaData, this.chunkIndex, this.totalBytes)));
                        if (this.isV5StyleAEAD) {
                            this.c.processAADBytes(Pack.longToBigEndian(this.totalBytes), 0, 8);
                        }
                        this.c.processBytes(this.buf, 0, this.tagLen, this.buf, 0);
                        this.c.doFinal(this.buf, 0);
                    } catch (InvalidCipherTextException e) {
                        throw new IOException("exception processing final tag: " + e.getMessage());
                    }
                } else {
                    Streams.readFully(this.in, this.buf, this.tagLen, this.tagLen);
                }
                return bArrProcessAEADData;
            } catch (InvalidCipherTextException 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: classes2.dex */
    protected static class PGPAeadOutputStream extends OutputStream {
        private final byte[] aaData;
        private final AEADBlockCipher c;
        private final int chunkLength;
        private final byte[] data;
        private int dataOff;
        private final boolean isV5StyleAEAD;
        private final byte[] iv;
        private final OutputStream out;
        private final KeyParameter secretKey;
        private final int tagLen;
        private long chunkIndex = 0;
        private long totalBytes = 0;

        public PGPAeadOutputStream(boolean z, OutputStream outputStream, AEADBlockCipher aEADBlockCipher, KeyParameter keyParameter, byte[] bArr, int i, int i2, int i3) {
            this.isV5StyleAEAD = z;
            this.out = outputStream;
            this.iv = bArr;
            this.chunkLength = (int) BcAEADUtil.getChunkLength(i3);
            this.tagLen = AEADUtils.getAuthTagLength(i2);
            this.data = new byte[this.chunkLength];
            this.c = aEADBlockCipher;
            this.secretKey = keyParameter;
            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();
            }
            boolean z = this.isV5StyleAEAD;
            try {
                this.c.init(true, new AEADParameters(this.secretKey, 128, BcAEADUtil.getNonce(this.iv, this.chunkIndex), PGPAeadInputStream.getAdata(z, this.aaData, this.chunkIndex, this.totalBytes)));
                if (z) {
                    this.c.processAADBytes(Pack.longToBigEndian(this.totalBytes), 0, 8);
                }
                this.c.doFinal(this.data, 0);
                this.out.write(this.data, 0, this.tagLen);
                this.out.close();
            } catch (InvalidCipherTextException e) {
                throw new IOException("exception processing final tag: " + e.getMessage());
            }
        }

        private void writeBlock() throws IOException {
            boolean z = this.isV5StyleAEAD;
            byte[] bArr = new byte[z ? 13 : this.aaData.length];
            System.arraycopy(this.aaData, 0, bArr, 0, this.aaData.length);
            if (z) {
                BcAEADUtil.xorChunkId(bArr, this.chunkIndex);
            }
            try {
                this.c.init(true, new AEADParameters(this.secretKey, 128, BcAEADUtil.getNonce(this.iv, this.chunkIndex), bArr));
                this.out.write(this.data, 0, this.c.processBytes(this.data, 0, this.dataOff, this.data, 0));
                this.out.write(this.data, 0, this.c.doFinal(this.data, 0));
                this.totalBytes += (long) this.dataOff;
                this.chunkIndex++;
                this.dataOff = 0;
            } catch (InvalidCipherTextException 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 static AEADBlockCipher createAEADCipher(int i, int i2) throws PGPException {
        Engine engine;
        if (i == 7 || i == 8 || i == 9) {
            engine = new Engine() { // from class: org.bouncycastle.openpgp.operator.bc.BcAEADUtil.1
                @Override // org.bouncycastle.openpgp.operator.bc.BcAEADUtil.Engine
                public BlockCipher newInstance() {
                    return AESEngine.newInstance();
                }
            };
        } else {
            if (i != 11 && i != 12 && i != 13) {
                throw new PGPException("AEAD only supported for AES and Camellia based algorithms");
            }
            engine = new Engine() { // from class: org.bouncycastle.openpgp.operator.bc.BcAEADUtil.2
                @Override // org.bouncycastle.openpgp.operator.bc.BcAEADUtil.Engine
                public BlockCipher newInstance() {
                    return new CamelliaEngine();
                }
            };
        }
        return createAEADCipher(i2, engine);
    }

    private static AEADBlockCipher createAEADCipher(int i, Engine engine) throws PGPException {
        switch (i) {
            case 1:
                return new EAXBlockCipher(engine.newInstance());
            case 2:
                return new OCBBlockCipher(engine.newInstance(), engine.newInstance());
            case 3:
                return GCMBlockCipher.newInstance(engine.newInstance());
            default:
                throw new PGPException("unrecognised AEAD algorithm: " + i);
        }
    }

    static 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();
        final KeyParameter keyParameter = new KeyParameter(key);
        final AEADBlockCipher aEADBlockCipherCreateAEADCipher = createAEADCipher(algorithm, aEADAlgorithm);
        return new PGPDataDecryptor() { // from class: org.bouncycastle.openpgp.operator.bc.BcAEADUtil.3
            @Override // org.bouncycastle.openpgp.operator.PGPDataDecryptor
            public int getBlockSize() {
                return aEADBlockCipherCreateAEADCipher.getUnderlyingCipher().getBlockSize();
            }

            @Override // org.bouncycastle.openpgp.operator.PGPDataDecryptor
            public InputStream getInputStream(InputStream inputStream) {
                try {
                    return new PGPAeadInputStream(true, inputStream, aEADBlockCipherCreateAEADCipher, keyParameter, 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();
            }
        };
    }

    static PGPDataDecryptor createOpenPgpV6DataDecryptor(SymmetricEncIntegrityPacket symmetricEncIntegrityPacket, PGPSessionKey pGPSessionKey) throws PGPException {
        if (symmetricEncIntegrityPacket.getVersion() == 1) {
            throw new PGPException("SEIPD packet MUST be of version 2 or greater.");
        }
        final int cipherAlgorithm = symmetricEncIntegrityPacket.getCipherAlgorithm();
        final int aeadAlgorithm = symmetricEncIntegrityPacket.getAeadAlgorithm();
        final int chunkSize = symmetricEncIntegrityPacket.getChunkSize();
        final byte[] aAData = symmetricEncIntegrityPacket.getAAData();
        byte[][] bArrDeriveMessageKeyAndIv = deriveMessageKeyAndIv(aeadAlgorithm, cipherAlgorithm, pGPSessionKey.getKey(), symmetricEncIntegrityPacket.getSalt(), aAData);
        byte[] bArr = bArrDeriveMessageKeyAndIv[0];
        final byte[] bArr2 = bArrDeriveMessageKeyAndIv[1];
        final KeyParameter keyParameter = new KeyParameter(bArr);
        final AEADBlockCipher aEADBlockCipherCreateAEADCipher = createAEADCipher(cipherAlgorithm, aeadAlgorithm);
        return new PGPDataDecryptor() { // from class: org.bouncycastle.openpgp.operator.bc.BcAEADUtil.4
            @Override // org.bouncycastle.openpgp.operator.PGPDataDecryptor
            public int getBlockSize() {
                return aEADBlockCipherCreateAEADCipher.getUnderlyingCipher().getBlockSize();
            }

            @Override // org.bouncycastle.openpgp.operator.PGPDataDecryptor
            public InputStream getInputStream(InputStream inputStream) {
                try {
                    return new PGPAeadInputStream(false, inputStream, aEADBlockCipherCreateAEADCipher, keyParameter, 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();
            }
        };
    }

    static byte[][] deriveMessageKeyAndIv(int i, int i2, byte[] bArr, byte[] bArr2, byte[] bArr3) {
        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[] processAEADData(boolean z, int i, int i2, byte[] bArr, byte[] bArr2, byte[] bArr3, byte[] bArr4, int i3, int i4, String str) throws PGPException {
        try {
            return processAEADData(z, createAEADCipher(i, i2), new KeyParameter(bArr), bArr2, bArr3, bArr4, i3, i4);
        } catch (InvalidCipherTextException e) {
            throw new PGPException(str, e);
        }
    }

    static byte[] processAEADData(boolean z, AEADBlockCipher aEADBlockCipher, KeyParameter keyParameter, byte[] bArr, byte[] bArr2, byte[] bArr3, int i, int i2) throws InvalidCipherTextException {
        aEADBlockCipher.init(z, new AEADParameters(keyParameter, 128, bArr, bArr2));
        byte[] bArr4 = new byte[aEADBlockCipher.getOutputSize(i2)];
        aEADBlockCipher.doFinal(bArr4, aEADBlockCipher.processBytes(bArr3, i, i2, bArr4, 0));
        return bArr4;
    }

    static byte[] processAeadKeyData(boolean z, int i, int i2, byte[] bArr, byte[] bArr2, int i3, int i4, byte[] bArr3, int i5, int i6, byte[] bArr4) throws PGPException {
        byte b = (byte) (i3 | 192);
        return processAEADData(z, i, i2, generateHKDFBytes(bArr, null, new byte[]{b, (byte) i4, (byte) i, (byte) i2}, SymmetricKeyUtils.getKeyLengthInOctets(i)), bArr2, Arrays.prepend(bArr4, b), bArr3, i5, i6, ProcessAeadKeyDataErrorMessage);
    }

    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]);
    }
}
