package com.ifpdos.certinstaller;

import android.app.KeyguardManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.os.UserHandle;
import android.security.Credentials;
import android.security.IKeyChainService;
import android.text.TextUtils;
import android.util.Log;
import com.android.org.conscrypt.TrustedCertificateStore;
import g2.j;
import g2.t;
import g2.v0;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/* JADX INFO: compiled from: CredentialHelper.java */
/* JADX INFO: loaded from: classes.dex */
class a {

    /* JADX INFO: renamed from: i, reason: collision with root package name */
    private static final String[] f4437i = {"com.android.settings", "com.ifpdos.vsettings", "com.ifpdos.settings", "com.ifpdos.vssettings", "com.ifpdos.touchpanel"};

    /* JADX INFO: renamed from: a, reason: collision with root package name */
    private HashMap<String, byte[]> f4438a;

    /* JADX INFO: renamed from: b, reason: collision with root package name */
    private String f4439b;

    /* JADX INFO: renamed from: c, reason: collision with root package name */
    private String f4440c;

    /* JADX INFO: renamed from: d, reason: collision with root package name */
    private String f4441d;

    /* JADX INFO: renamed from: e, reason: collision with root package name */
    private int f4442e;

    /* JADX INFO: renamed from: f, reason: collision with root package name */
    private PrivateKey f4443f;

    /* JADX INFO: renamed from: g, reason: collision with root package name */
    private X509Certificate f4444g;

    /* JADX INFO: renamed from: h, reason: collision with root package name */
    private List<X509Certificate> f4445h;

    a() {
        this.f4438a = new HashMap<>();
        this.f4439b = "";
        this.f4440c = "";
        this.f4441d = "";
        this.f4442e = -1;
        this.f4445h = new ArrayList();
    }

    private boolean e(KeyStore.PasswordProtection passwordProtection) throws Exception {
        KeyStore keyStoreU = u(passwordProtection);
        Enumeration<String> enumerationAliases = keyStoreU.aliases();
        if (!enumerationAliases.hasMoreElements()) {
            Log.e("CredentialHelper", "PKCS12 file has no elements");
            return false;
        }
        while (enumerationAliases.hasMoreElements()) {
            String strNextElement = enumerationAliases.nextElement();
            if (keyStoreU.isKeyEntry(strNextElement)) {
                KeyStore.Entry entry = keyStoreU.getEntry(strNextElement, passwordProtection);
                Log.d("CredentialHelper", "extracted alias = " + strNextElement + ", entry=" + entry.getClass());
                if (entry instanceof KeyStore.PrivateKeyEntry) {
                    if (TextUtils.isEmpty(this.f4439b)) {
                        this.f4439b = strNextElement;
                    }
                    return r((KeyStore.PrivateKeyEntry) entry);
                }
            } else {
                Log.d("CredentialHelper", "Skip non-key entry, alias = " + strNextElement);
            }
        }
        return true;
    }

    private synchronized boolean r(KeyStore.PrivateKeyEntry privateKeyEntry) {
        this.f4443f = privateKeyEntry.getPrivateKey();
        this.f4444g = (X509Certificate) privateKeyEntry.getCertificate();
        Certificate[] certificateChain = privateKeyEntry.getCertificateChain();
        Log.d("CredentialHelper", "# certs extracted = " + certificateChain.length);
        this.f4445h = new ArrayList(certificateChain.length);
        for (Certificate certificate : certificateChain) {
            X509Certificate x509Certificate = (X509Certificate) certificate;
            if (t(x509Certificate)) {
                this.f4445h.add(x509Certificate);
            }
        }
        Log.d("CredentialHelper", "# ca certs extracted = " + this.f4445h.size());
        return true;
    }

    private boolean t(X509Certificate x509Certificate) {
        try {
            byte[] extensionValue = x509Certificate.getExtensionValue("2.5.29.19");
            if (extensionValue == null) {
                return false;
            }
            return h2.a.h((t) new j(((v0) new j(extensionValue).h()).p()).h()).i();
        } catch (IOException unused) {
            return false;
        }
    }

    private KeyStore u(KeyStore.PasswordProtection passwordProtection) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(new ByteArrayInputStream(g("PKCS12")), passwordProtection.getPassword());
        return keyStore;
    }

    private void v(Context context, String str) {
        if (((KeyguardManager) context.getSystemService(KeyguardManager.class)).isDeviceSecure(UserHandle.myUserId())) {
            ((DevicePolicyManager) context.getSystemService(DevicePolicyManager.class)).approveCaCert(str, UserHandle.myUserId(), true);
        }
    }

    private void y(byte[] bArr) {
        if (bArr == null) {
            return;
        }
        try {
            X509Certificate x509Certificate = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(bArr));
            if (t(x509Certificate)) {
                Log.d("CredentialHelper", "got a CA cert");
                this.f4445h.add(x509Certificate);
            } else {
                Log.d("CredentialHelper", "got a user cert");
                this.f4444g = x509Certificate;
            }
        } catch (CertificateException e3) {
            Log.w("CredentialHelper", "parseCert(): " + e3);
        }
    }

    void A(String str) {
        this.f4439b = str;
    }

    void B(String str, byte[] bArr) {
        try {
            this.f4443f = KeyFactory.getInstance(str).generatePrivate(new PKCS8EncodedKeySpec(bArr));
        } catch (NoSuchAlgorithmException e3) {
            throw new AssertionError(e3);
        } catch (InvalidKeySpecException e4) {
            throw new AssertionError(e4);
        }
    }

    boolean a() {
        return this.f4441d != null && Arrays.toString(f4437i).contains(this.f4441d);
    }

    boolean b() {
        return !this.f4438a.isEmpty();
    }

    Intent c(Context context) {
        Intent intent = new Intent("com.android.credentials.INSTALL");
        intent.setComponent(ComponentName.unflattenFromString(context.getString(R.string.config_system_install_component)));
        intent.putExtra("install_as_uid", this.f4442e);
        intent.putExtra("user_key_pair_name", this.f4439b);
        try {
            PrivateKey privateKey = this.f4443f;
            if (privateKey != null) {
                intent.putExtra("user_private_key_data", privateKey.getEncoded());
            }
            X509Certificate x509Certificate = this.f4444g;
            if (x509Certificate != null) {
                intent.putExtra("user_certificate_data", Credentials.convertToPem(new Certificate[]{x509Certificate}));
            }
            if (!this.f4445h.isEmpty()) {
                List<X509Certificate> list = this.f4445h;
                intent.putExtra("ca_certificates_data", Credentials.convertToPem((X509Certificate[]) list.toArray(new X509Certificate[list.size()])));
            }
            return intent;
        } catch (IOException e3) {
            throw new AssertionError(e3);
        } catch (CertificateEncodingException e4) {
            throw new AssertionError(e4);
        }
    }

    boolean d(String str) {
        try {
            return e(new KeyStore.PasswordProtection(str.toCharArray()));
        } catch (Exception e3) {
            Log.w("CredentialHelper", "extractPkcs12(): " + e3, e3);
            return false;
        }
    }

    String f() {
        return this.f4440c;
    }

    byte[] g(String str) {
        return this.f4438a.get(str);
    }

    String h() {
        return this.f4439b;
    }

    public String i() {
        return this.f4441d;
    }

    int j(String str) {
        return "wifi".equals(str) ? 1010 : -1;
    }

    boolean k() {
        return this.f4443f != null || q() || l();
    }

    boolean l() {
        return !this.f4445h.isEmpty();
    }

    public boolean m() {
        return l() && this.f4442e == -1 && this.f4443f == null;
    }

    boolean n() {
        if (!o()) {
            return false;
        }
        try {
            return u(new KeyStore.PasswordProtection(new char[0])) == null;
        } catch (Exception unused) {
            return true;
        }
    }

    boolean o() {
        return this.f4438a.containsKey("PKCS12");
    }

    boolean p() {
        return this.f4438a.containsKey("PKEY");
    }

    boolean q() {
        return this.f4444g != null;
    }

    boolean s(Context context, IKeyChainService iKeyChainService) {
        TrustedCertificateStore trustedCertificateStore = new TrustedCertificateStore();
        for (X509Certificate x509Certificate : this.f4445h) {
            try {
                byte[] encoded = x509Certificate.getEncoded();
                if (encoded != null) {
                    try {
                        iKeyChainService.installCaCertificate(encoded);
                        String certificateAlias = trustedCertificateStore.getCertificateAlias(x509Certificate);
                        if (certificateAlias == null) {
                            Log.e("CredentialHelper", "alias is null");
                            return false;
                        }
                        v(context, certificateAlias);
                    } catch (RemoteException e3) {
                        Log.w("CredentialHelper", "installCaCertsToKeyChain(): " + e3);
                        return false;
                    }
                }
            } catch (CertificateEncodingException e4) {
                throw new AssertionError(e4);
            }
        }
        return true;
    }

    void w(Bundle bundle) {
        this.f4438a = (HashMap) bundle.getSerializable("data");
        this.f4439b = bundle.getString("name");
        this.f4442e = bundle.getInt("install_as_uid", -1);
        String string = bundle.getString("user_key_algorithm");
        byte[] byteArray = bundle.getByteArray("USRPKEY_");
        Log.d("CredentialHelper", "Loaded key algorithm: " + string);
        if (string != null && byteArray != null) {
            B(string, byteArray);
        }
        Iterator it = ((ArrayList) b.a(bundle.getByteArray("crts"))).iterator();
        while (it.hasNext()) {
            y((byte[]) it.next());
        }
    }

    synchronized void x(Bundle bundle) {
        try {
            bundle.putSerializable("data", this.f4438a);
            bundle.putString("name", this.f4439b);
            bundle.putInt("install_as_uid", this.f4442e);
            if (this.f4443f != null) {
                Log.d("CredentialHelper", "Key algorithm: " + this.f4443f.getAlgorithm());
                bundle.putString("user_key_algorithm", this.f4443f.getAlgorithm());
                bundle.putByteArray("USRPKEY_", this.f4443f.getEncoded());
            }
            ArrayList arrayList = new ArrayList(this.f4445h.size() + 1);
            X509Certificate x509Certificate = this.f4444g;
            if (x509Certificate != null) {
                arrayList.add(x509Certificate.getEncoded());
            }
            Iterator<X509Certificate> it = this.f4445h.iterator();
            while (it.hasNext()) {
                arrayList.add(it.next().getEncoded());
            }
            bundle.putByteArray("crts", b.c(arrayList));
        } catch (CertificateEncodingException e3) {
            throw new AssertionError(e3);
        }
    }

    void z(String str) {
        this.f4440c = str;
        this.f4442e = j(str);
    }

    a(Map<String, byte[]> map, String str, String str2, String str3, int i3) {
        this.f4438a = new HashMap<>();
        this.f4439b = "";
        this.f4440c = "";
        this.f4441d = "";
        this.f4442e = -1;
        this.f4445h = new ArrayList();
        if (str != null) {
            this.f4439b = str;
        }
        if (str2 != null) {
            this.f4441d = str2;
        }
        if (str3 != null) {
            z(str3);
        } else {
            this.f4442e = i3;
        }
        for (String str4 : map.keySet()) {
            byte[] bArr = map.get(str4);
            StringBuilder sb = new StringBuilder();
            sb.append("   ");
            sb.append(str4);
            sb.append(": ");
            sb.append(bArr == null ? -1 : bArr.length);
            Log.d("CredentialHelper", sb.toString());
            this.f4438a.put(str4, bArr);
        }
        y(g("CERT"));
    }
}
