package org.bouncycastle.openpgp.operator.jcajce;

import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.interfaces.RSAKey;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
import javax.crypto.Cipher;
import javax.crypto.interfaces.DHKey;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.edec.EdECObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x9.ECNamedCurveTable;
import org.bouncycastle.bcpg.AEADEncDataPacket;
import org.bouncycastle.bcpg.ECDHPublicBCPGKey;
import org.bouncycastle.bcpg.PublicKeyPacket;
import org.bouncycastle.bcpg.SymmetricEncIntegrityPacket;
import org.bouncycastle.jcajce.spec.UserKeyingMaterialSpec;
import org.bouncycastle.jcajce.spec.XDHParameterSpec;
import org.bouncycastle.jcajce.util.DefaultJcaJceHelper;
import org.bouncycastle.jcajce.util.NamedJcaJceHelper;
import org.bouncycastle.jcajce.util.ProviderJcaJceHelper;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSessionKey;
import org.bouncycastle.openpgp.operator.AbstractPublicKeyDataDecryptorFactory;
import org.bouncycastle.openpgp.operator.PGPDataDecryptor;
import org.bouncycastle.openpgp.operator.PGPPad;
import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory;
import org.bouncycastle.openpgp.operator.RFC6637Utils;
import org.bouncycastle.util.Arrays;

/* JADX INFO: loaded from: classes.dex */
public class JcePublicKeyDataDecryptorFactoryBuilder {
    private OperatorHelper helper = new OperatorHelper(new DefaultJcaJceHelper());
    private OperatorHelper contentHelper = new OperatorHelper(new DefaultJcaJceHelper());
    private JceAEADUtil aeadHelper = new JceAEADUtil(this.contentHelper);
    private JcaPGPKeyConverter keyConverter = new JcaPGPKeyConverter();
    private JcaKeyFingerprintCalculator fingerprintCalculator = new JcaKeyFingerprintCalculator();

    private static void checkRange(int i, byte[] bArr) throws PGPException {
        if (i > bArr.length) {
            throw new PGPException("encoded length out of range");
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public byte[] decryptSessionData(int i, PrivateKey privateKey, int i2, byte[][] bArr) throws PGPException {
        Cipher cipherCreatePublicKeyCipher = this.helper.createPublicKeyCipher(i);
        try {
            cipherCreatePublicKeyCipher.init(2, privateKey);
            if (i == 2 || i == 1) {
                updateWithMPI(cipherCreatePublicKeyCipher, i2, bArr[0]);
            } else {
                updateWithMPI(cipherCreatePublicKeyCipher, i2, bArr[0]);
                updateWithMPI(cipherCreatePublicKeyCipher, i2, bArr[1]);
            }
            try {
                return cipherCreatePublicKeyCipher.doFinal();
            } catch (Exception e) {
                throw new PGPException("exception decrypting session data", e);
            }
        } catch (InvalidKeyException e2) {
            throw new PGPException("error setting asymmetric cipher", e2);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public byte[] decryptSessionData(JcaPGPKeyConverter jcaPGPKeyConverter, PGPPrivateKey pGPPrivateKey, byte[] bArr, int i, String str, int i2, ASN1ObjectIdentifier aSN1ObjectIdentifier, String str2, boolean z) throws PGPException {
        try {
            byte[] bArrCopyOf = Arrays.copyOf(bArr, i);
            int i3 = bArr[i] & 255;
            int i4 = i + 1;
            checkRange(i4 + i3, bArr);
            int i5 = i3 - (z ? 1 : 0);
            int i6 = i4 + (z ? 1 : 0);
            return getSessionKey(jcaPGPKeyConverter, pGPPrivateKey, str, getPublicKey(bArrCopyOf, aSN1ObjectIdentifier, 0), i2, Arrays.copyOfRange(bArr, i6, i5 + i6), JcaJcePGPUtil.getHybridValueParameterSpecWithPrepend(bArrCopyOf, pGPPrivateKey.getPublicKeyPacket(), str2)).getEncoded();
        } catch (Exception e) {
            throw new PGPException("error decrypting session data: " + e.getMessage(), e);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public byte[] decryptSessionData(JcaPGPKeyConverter jcaPGPKeyConverter, PGPPrivateKey pGPPrivateKey, byte[][] bArr) throws PGPException {
        String agreementAlgorithm;
        PublicKey publicKey;
        ASN1ObjectIdentifier aSN1ObjectIdentifier;
        PublicKeyPacket publicKeyPacket = pGPPrivateKey.getPublicKeyPacket();
        byte[] bArr2 = bArr[0];
        int i = ((((bArr2[0] & 255) << 8) + (bArr2[1] & 255)) + 7) / 8;
        int i2 = i + 2;
        int i3 = i2 + 1;
        checkRange(i3, bArr2);
        byte[] bArr3 = new byte[i];
        System.arraycopy(bArr2, 2, bArr3, 0, i);
        int i4 = bArr2[i2] & 255;
        checkRange(i3 + i4, bArr2);
        byte[] bArr4 = new byte[i4];
        System.arraycopy(bArr2, i3, bArr4, 0, i4);
        try {
            ECDHPublicBCPGKey eCDHPublicBCPGKey = (ECDHPublicBCPGKey) publicKeyPacket.getKey();
            if (!JcaJcePGPUtil.isX25519(eCDHPublicBCPGKey.getCurveOID())) {
                if (eCDHPublicBCPGKey.getCurveOID().equals((ASN1Primitive) EdECObjectIdentifiers.id_X448)) {
                    agreementAlgorithm = RFC6637Utils.getXDHAlgorithm(publicKeyPacket);
                    if (i != 57 || 64 != bArr3[0]) {
                        throw new IllegalArgumentException("Invalid Curve25519 public key");
                    }
                    aSN1ObjectIdentifier = EdECObjectIdentifiers.id_X448;
                } else {
                    ECPoint eCPointDecodePoint = ECNamedCurveTable.getByOIDLazy(eCDHPublicBCPGKey.getCurveOID()).getCurve().decodePoint(bArr3);
                    agreementAlgorithm = RFC6637Utils.getAgreementAlgorithm(publicKeyPacket);
                    publicKey = jcaPGPKeyConverter.getPublicKey(new PGPPublicKey(new PublicKeyPacket(publicKeyPacket.getVersion(), 18, new Date(), new ECDHPublicBCPGKey(eCDHPublicBCPGKey.getCurveOID(), eCPointDecodePoint, eCDHPublicBCPGKey.getHashAlgorithm(), eCDHPublicBCPGKey.getSymmetricKeyAlgorithm())), this.fingerprintCalculator));
                }
                return PGPPad.unpadSessionData(getSessionKey(jcaPGPKeyConverter, pGPPrivateKey, agreementAlgorithm, publicKey, eCDHPublicBCPGKey.getSymmetricKeyAlgorithm(), bArr4, new UserKeyingMaterialSpec(RFC6637Utils.createUserKeyingMaterial(publicKeyPacket, this.fingerprintCalculator))).getEncoded());
            }
            agreementAlgorithm = RFC6637Utils.getXDHAlgorithm(publicKeyPacket);
            if (i != 33 || 64 != bArr3[0]) {
                throw new IllegalArgumentException("Invalid Curve25519 public key");
            }
            aSN1ObjectIdentifier = EdECObjectIdentifiers.id_X25519;
            publicKey = getPublicKey(bArr3, aSN1ObjectIdentifier, 1);
            return PGPPad.unpadSessionData(getSessionKey(jcaPGPKeyConverter, pGPPrivateKey, agreementAlgorithm, publicKey, eCDHPublicBCPGKey.getSymmetricKeyAlgorithm(), bArr4, new UserKeyingMaterialSpec(RFC6637Utils.createUserKeyingMaterial(publicKeyPacket, this.fingerprintCalculator))).getEncoded());
        } catch (Exception e) {
            throw new PGPException("error decrypting session data: " + e.getMessage(), e);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public int getExpectedPayloadSize(PrivateKey privateKey) {
        BigInteger modulus;
        if (privateKey instanceof DHKey) {
            modulus = ((DHKey) privateKey).getParams().getP();
        } else {
            if (!(privateKey instanceof RSAKey)) {
                return -1;
            }
            modulus = ((RSAKey) privateKey).getModulus();
        }
        return (modulus.bitLength() + 7) / 8;
    }

    private PublicKey getPublicKey(byte[] bArr, ASN1ObjectIdentifier aSN1ObjectIdentifier, int i) throws GeneralSecurityException, IOException, PGPException {
        return this.helper.createKeyFactory("XDH").generatePublic(new X509EncodedKeySpec(new SubjectPublicKeyInfo(new AlgorithmIdentifier(aSN1ObjectIdentifier), Arrays.copyOfRange(bArr, i, bArr.length)).getEncoded()));
    }

    private Key getSessionKey(JcaPGPKeyConverter jcaPGPKeyConverter, PGPPrivateKey pGPPrivateKey, String str, PublicKey publicKey, int i, byte[] bArr, AlgorithmParameterSpec algorithmParameterSpec) throws GeneralSecurityException, PGPException {
        Key secret = JcaJcePGPUtil.getSecret(this.helper, publicKey, RFC6637Utils.getKeyEncryptionOID(i).getId(), str, algorithmParameterSpec, jcaPGPKeyConverter.getPrivateKey(pGPPrivateKey));
        Cipher cipherCreateKeyWrapper = this.helper.createKeyWrapper(i);
        cipherCreateKeyWrapper.init(4, secret);
        return cipherCreateKeyWrapper.unwrap(bArr, "Session", 3);
    }

    private void updateWithMPI(Cipher cipher, int i, byte[] bArr) {
        int length;
        int i2 = 2;
        if (i <= 0) {
            length = bArr.length;
        } else if (bArr.length - 2 > i) {
            length = bArr.length;
            i2 = 3;
        } else {
            if (i > bArr.length - 2) {
                cipher.update(new byte[i - (bArr.length - 2)]);
            }
            length = bArr.length;
        }
        cipher.update(bArr, i2, length - i2);
    }

    public PublicKeyDataDecryptorFactory build(final PrivateKey privateKey) {
        return new AbstractPublicKeyDataDecryptorFactory(this) { // from class: org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder.1
            final int expectedPayLoadSize;
            final /* synthetic */ JcePublicKeyDataDecryptorFactoryBuilder this$0;

            {
                this.this$0 = this;
                this.expectedPayLoadSize = this.this$0.getExpectedPayloadSize(privateKey);
            }

            @Override // org.bouncycastle.openpgp.operator.PGPDataDecryptorFactory
            public PGPDataDecryptor createDataDecryptor(AEADEncDataPacket aEADEncDataPacket, PGPSessionKey pGPSessionKey) throws PGPException {
                return this.this$0.aeadHelper.createOpenPgpV5DataDecryptor(aEADEncDataPacket, pGPSessionKey);
            }

            @Override // org.bouncycastle.openpgp.operator.PGPDataDecryptorFactory
            public PGPDataDecryptor createDataDecryptor(SymmetricEncIntegrityPacket symmetricEncIntegrityPacket, PGPSessionKey pGPSessionKey) throws PGPException {
                return this.this$0.aeadHelper.createOpenPgpV6DataDecryptor(symmetricEncIntegrityPacket, pGPSessionKey);
            }

            @Override // org.bouncycastle.openpgp.operator.PGPDataDecryptorFactory
            public PGPDataDecryptor createDataDecryptor(boolean z, int i, byte[] bArr) throws PGPException {
                return this.this$0.contentHelper.createDataDecryptor(z, i, bArr);
            }

            @Override // org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory
            public byte[] recoverSessionData(int i, byte[][] bArr, int i2) throws PGPException {
                if (i == 18 || i == 25 || i == 26) {
                    throw new PGPException("ECDH requires use of PGPPrivateKey for decryption");
                }
                return this.this$0.decryptSessionData(i, privateKey, this.expectedPayLoadSize, bArr);
            }
        };
    }

    public PublicKeyDataDecryptorFactory build(final PGPPrivateKey pGPPrivateKey) {
        return new AbstractPublicKeyDataDecryptorFactory(this) { // from class: org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder.2
            final /* synthetic */ JcePublicKeyDataDecryptorFactoryBuilder this$0;

            {
                this.this$0 = this;
            }

            @Override // org.bouncycastle.openpgp.operator.PGPDataDecryptorFactory
            public PGPDataDecryptor createDataDecryptor(AEADEncDataPacket aEADEncDataPacket, PGPSessionKey pGPSessionKey) throws PGPException {
                return this.this$0.aeadHelper.createOpenPgpV5DataDecryptor(aEADEncDataPacket, pGPSessionKey);
            }

            @Override // org.bouncycastle.openpgp.operator.PGPDataDecryptorFactory
            public PGPDataDecryptor createDataDecryptor(SymmetricEncIntegrityPacket symmetricEncIntegrityPacket, PGPSessionKey pGPSessionKey) throws PGPException {
                return this.this$0.aeadHelper.createOpenPgpV6DataDecryptor(symmetricEncIntegrityPacket, pGPSessionKey);
            }

            @Override // org.bouncycastle.openpgp.operator.PGPDataDecryptorFactory
            public PGPDataDecryptor createDataDecryptor(boolean z, int i, byte[] bArr) throws PGPException {
                return this.this$0.contentHelper.createDataDecryptor(z, i, bArr);
            }

            @Override // org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory
            public byte[] recoverSessionData(int i, byte[][] bArr, int i2) throws PGPException {
                boolean zContainsSKAlg = containsSKAlg(i2);
                if (i == 18) {
                    return this.this$0.decryptSessionData(this.this$0.keyConverter, pGPPrivateKey, bArr);
                }
                if (i == 25) {
                    return this.this$0.decryptSessionData(this.this$0.keyConverter, pGPPrivateKey, bArr[0], 32, "X25519withSHA256HKDF", 7, EdECObjectIdentifiers.id_X25519, XDHParameterSpec.X25519, zContainsSKAlg);
                }
                JcePublicKeyDataDecryptorFactoryBuilder jcePublicKeyDataDecryptorFactoryBuilder = this.this$0;
                if (i == 26) {
                    return jcePublicKeyDataDecryptorFactoryBuilder.decryptSessionData(this.this$0.keyConverter, pGPPrivateKey, bArr[0], 56, "X448withSHA512HKDF", 9, EdECObjectIdentifiers.id_X448, XDHParameterSpec.X448, zContainsSKAlg);
                }
                PrivateKey privateKey = jcePublicKeyDataDecryptorFactoryBuilder.keyConverter.getPrivateKey(pGPPrivateKey);
                return this.this$0.decryptSessionData(i, privateKey, this.this$0.getExpectedPayloadSize(privateKey), bArr);
            }
        };
    }

    public JcePublicKeyDataDecryptorFactoryBuilder setContentProvider(String str) {
        this.contentHelper = new OperatorHelper(new NamedJcaJceHelper(str));
        this.aeadHelper = new JceAEADUtil(this.contentHelper);
        return this;
    }

    public JcePublicKeyDataDecryptorFactoryBuilder setContentProvider(Provider provider) {
        this.contentHelper = new OperatorHelper(new ProviderJcaJceHelper(provider));
        this.aeadHelper = new JceAEADUtil(this.contentHelper);
        return this;
    }

    public JcePublicKeyDataDecryptorFactoryBuilder setProvider(String str) {
        this.helper = new OperatorHelper(new NamedJcaJceHelper(str));
        this.keyConverter.setProvider(str);
        this.contentHelper = this.helper;
        this.aeadHelper = new JceAEADUtil(this.contentHelper);
        return this;
    }

    public JcePublicKeyDataDecryptorFactoryBuilder setProvider(Provider provider) {
        this.helper = new OperatorHelper(new ProviderJcaJceHelper(provider));
        this.keyConverter.setProvider(provider);
        this.contentHelper = this.helper;
        this.aeadHelper = new JceAEADUtil(this.contentHelper);
        return this;
    }
}
