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

package org.bouncycastle.x509;

import org.bouncycastle.asn1.x509.IssuingDistributionPoint;
import org.bouncycastle.asn1.x509.Extension;
import java.security.GeneralSecurityException;
import java.security.interfaces.DSAParams;
import java.security.spec.KeySpec;
import java.security.KeyFactory;
import java.security.spec.DSAPublicKeySpec;
import java.security.interfaces.DSAPublicKey;
import java.security.cert.X509CRLEntry;
import org.bouncycastle.asn1.ASN1Enumerated;
import java.security.cert.CRLException;
import java.math.BigInteger;
import org.bouncycastle.jcajce.PKIXCertStoreSelector;
import java.security.cert.CertStoreException;
import java.security.cert.CertSelector;
import java.security.cert.CertStore;
import java.security.cert.CertificateException;
import org.bouncycastle.util.StoreException;
import java.security.cert.Certificate;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import org.bouncycastle.util.Encodable;
import org.bouncycastle.util.Selector;
import org.bouncycastle.util.Store;
import org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory;
import java.util.Collection;
import org.bouncycastle.asn1.x509.PolicyInformation;
import java.util.Map;
import java.security.cert.PolicyNode;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.List;
import org.bouncycastle.jce.provider.PKIXPolicyNode;
import java.util.Enumeration;
import java.io.IOException;
import java.security.cert.PolicyQualifierInfo;
import org.bouncycastle.asn1.ASN1Encodable;
import java.io.OutputStream;
import org.bouncycastle.asn1.ASN1OutputStream;
import java.io.ByteArrayOutputStream;
import java.util.HashSet;
import java.util.Set;
import org.bouncycastle.asn1.ASN1Sequence;
import java.security.cert.CertPathValidatorException;
import org.bouncycastle.jce.exception.ExtCertPathValidatorException;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import java.security.PublicKey;
import java.security.cert.X509CRL;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.jce.provider.AnnotatedException;
import org.bouncycastle.asn1.ASN1Primitive;
import java.security.cert.X509Extension;
import java.util.Date;
import java.security.cert.PKIXParameters;
import java.security.cert.X509Certificate;
import javax.security.auth.x500.X500Principal;

class CertPathValidatorUtilities
{
    protected static final String CERTIFICATE_POLICIES;
    protected static final String BASIC_CONSTRAINTS;
    protected static final String POLICY_MAPPINGS;
    protected static final String SUBJECT_ALTERNATIVE_NAME;
    protected static final String NAME_CONSTRAINTS;
    protected static final String KEY_USAGE;
    protected static final String INHIBIT_ANY_POLICY;
    protected static final String ISSUING_DISTRIBUTION_POINT;
    protected static final String DELTA_CRL_INDICATOR;
    protected static final String POLICY_CONSTRAINTS;
    protected static final String CRL_NUMBER;
    protected static final String ANY_POLICY = "2.5.29.32.0";
    protected static final int KEY_CERT_SIGN = 5;
    protected static final int CRL_SIGN = 6;
    protected static final String[] crlReasons;
    
    protected static X500Principal getEncodedIssuerPrincipal(final Object o) {
        if (o instanceof X509Certificate) {
            return ((X509Certificate)o).getIssuerX500Principal();
        }
        return (X500Principal)((X509AttributeCertificate)o).getIssuer().getPrincipals()[0];
    }
    
    protected static Date getValidityDate(final PKIXParameters pkixParameters, final Date date) {
        final Date date2 = pkixParameters.getDate();
        return (null == date2) ? date : date2;
    }
    
    protected static X500Principal getSubjectPrincipal(final X509Certificate x509Certificate) {
        return x509Certificate.getSubjectX500Principal();
    }
    
    protected static boolean isSelfIssued(final X509Certificate x509Certificate) {
        return x509Certificate.getSubjectDN().equals(x509Certificate.getIssuerDN());
    }
    
    protected static ASN1Primitive getExtensionValue(final X509Extension x509Extension, final String s) throws AnnotatedException {
        final byte[] extensionValue = x509Extension.getExtensionValue(s);
        if (extensionValue == null) {
            return null;
        }
        return getObject(s, extensionValue);
    }
    
    private static ASN1Primitive getObject(final String str, final byte[] array) throws AnnotatedException {
        try {
            return new ASN1InputStream(((ASN1OctetString)new ASN1InputStream(array).readObject()).getOctets()).readObject();
        }
        catch (final Exception ex) {
            throw new AnnotatedException("exception processing extension " + str, ex);
        }
    }
    
    protected static X500Principal getIssuerPrincipal(final X509CRL x509CRL) {
        return x509CRL.getIssuerX500Principal();
    }
    
    protected static AlgorithmIdentifier getAlgorithmIdentifier(final PublicKey publicKey) throws CertPathValidatorException {
        try {
            return SubjectPublicKeyInfo.getInstance(new ASN1InputStream(publicKey.getEncoded()).readObject()).getAlgorithmId();
        }
        catch (final Exception ex) {
            throw new ExtCertPathValidatorException("Subject public key cannot be decoded.", ex);
        }
    }
    
    protected static final Set getQualifierSet(final ASN1Sequence asn1Sequence) throws CertPathValidatorException {
        final HashSet set = new HashSet();
        if (asn1Sequence == null) {
            return set;
        }
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        final ASN1OutputStream create = ASN1OutputStream.create(byteArrayOutputStream);
        final Enumeration objects = asn1Sequence.getObjects();
        while (objects.hasMoreElements()) {
            try {
                create.writeObject((ASN1Encodable)objects.nextElement());
                set.add(new PolicyQualifierInfo(byteArrayOutputStream.toByteArray()));
            }
            catch (final IOException ex) {
                throw new ExtCertPathValidatorException("Policy qualifier info cannot be decoded.", ex);
            }
            byteArrayOutputStream.reset();
        }
        return set;
    }
    
    protected static PKIXPolicyNode removePolicyNode(final PKIXPolicyNode pkixPolicyNode, final List[] array, final PKIXPolicyNode pkixPolicyNode2) {
        final PKIXPolicyNode pkixPolicyNode3 = (PKIXPolicyNode)pkixPolicyNode2.getParent();
        if (pkixPolicyNode == null) {
            return null;
        }
        if (pkixPolicyNode3 == null) {
            for (int i = 0; i < array.length; ++i) {
                array[i] = new ArrayList();
            }
            return null;
        }
        pkixPolicyNode3.removeChild(pkixPolicyNode2);
        removePolicyNodeRecurse(array, pkixPolicyNode2);
        return pkixPolicyNode;
    }
    
    private static void removePolicyNodeRecurse(final List[] array, final PKIXPolicyNode pkixPolicyNode) {
        array[pkixPolicyNode.getDepth()].remove(pkixPolicyNode);
        if (pkixPolicyNode.hasChildren()) {
            final Iterator children = pkixPolicyNode.getChildren();
            while (children.hasNext()) {
                removePolicyNodeRecurse(array, (PKIXPolicyNode)children.next());
            }
        }
    }
    
    protected static boolean processCertD1i(final int n, final List[] array, final ASN1ObjectIdentifier asn1ObjectIdentifier, final Set set) {
        final List list = array[n - 1];
        for (int i = 0; i < list.size(); ++i) {
            final PKIXPolicyNode pkixPolicyNode = list.get(i);
            if (pkixPolicyNode.getExpectedPolicies().contains(asn1ObjectIdentifier.getId())) {
                final HashSet set2 = new HashSet();
                set2.add(asn1ObjectIdentifier.getId());
                final PKIXPolicyNode pkixPolicyNode2 = new PKIXPolicyNode(new ArrayList(), n, set2, pkixPolicyNode, set, asn1ObjectIdentifier.getId(), false);
                pkixPolicyNode.addChild(pkixPolicyNode2);
                array[n].add(pkixPolicyNode2);
                return true;
            }
        }
        return false;
    }
    
    protected static void processCertD1ii(final int n, final List[] array, final ASN1ObjectIdentifier asn1ObjectIdentifier, final Set set) {
        final List list = array[n - 1];
        for (int i = 0; i < list.size(); ++i) {
            final PKIXPolicyNode pkixPolicyNode = list.get(i);
            if ("2.5.29.32.0".equals(pkixPolicyNode.getValidPolicy())) {
                final HashSet set2 = new HashSet();
                set2.add(asn1ObjectIdentifier.getId());
                final PKIXPolicyNode pkixPolicyNode2 = new PKIXPolicyNode(new ArrayList(), n, set2, pkixPolicyNode, set, asn1ObjectIdentifier.getId(), false);
                pkixPolicyNode.addChild(pkixPolicyNode2);
                array[n].add(pkixPolicyNode2);
                return;
            }
        }
    }
    
    protected static void prepareNextCertB1(final int n, final List[] array, final String anObject, final Map map, final X509Certificate x509Certificate) throws AnnotatedException, CertPathValidatorException {
        boolean b = false;
        for (final PKIXPolicyNode pkixPolicyNode : array[n]) {
            if (pkixPolicyNode.getValidPolicy().equals(anObject)) {
                b = true;
                pkixPolicyNode.setExpectedPolicies(map.get(anObject));
                break;
            }
        }
        if (!b) {
            for (final PKIXPolicyNode pkixPolicyNode2 : array[n]) {
                if ("2.5.29.32.0".equals(pkixPolicyNode2.getValidPolicy())) {
                    Set qualifierSet = null;
                    ASN1Sequence instance;
                    try {
                        instance = ASN1Sequence.getInstance(getExtensionValue(x509Certificate, CertPathValidatorUtilities.CERTIFICATE_POLICIES));
                    }
                    catch (final Exception ex) {
                        throw new AnnotatedException("Certificate policies cannot be decoded.", ex);
                    }
                    final Enumeration objects = instance.getObjects();
                    while (objects.hasMoreElements()) {
                        PolicyInformation instance2;
                        try {
                            instance2 = PolicyInformation.getInstance(objects.nextElement());
                        }
                        catch (final Exception ex2) {
                            throw new AnnotatedException("Policy information cannot be decoded.", ex2);
                        }
                        if ("2.5.29.32.0".equals(instance2.getPolicyIdentifier().getId())) {
                            try {
                                qualifierSet = getQualifierSet(instance2.getPolicyQualifiers());
                                break;
                            }
                            catch (final CertPathValidatorException ex3) {
                                throw new ExtCertPathValidatorException("Policy qualifier info set could not be built.", ex3);
                            }
                        }
                    }
                    boolean contains = false;
                    if (x509Certificate.getCriticalExtensionOIDs() != null) {
                        contains = x509Certificate.getCriticalExtensionOIDs().contains(CertPathValidatorUtilities.CERTIFICATE_POLICIES);
                    }
                    final PKIXPolicyNode pkixPolicyNode3 = (PKIXPolicyNode)pkixPolicyNode2.getParent();
                    if ("2.5.29.32.0".equals(pkixPolicyNode3.getValidPolicy())) {
                        final PKIXPolicyNode pkixPolicyNode4 = new PKIXPolicyNode(new ArrayList(), n, map.get(anObject), pkixPolicyNode3, qualifierSet, anObject, contains);
                        pkixPolicyNode3.addChild(pkixPolicyNode4);
                        array[n].add(pkixPolicyNode4);
                        break;
                    }
                    break;
                }
            }
        }
    }
    
    protected static PKIXPolicyNode prepareNextCertB2(final int n, final List[] array, final String anObject, PKIXPolicyNode removePolicyNode) {
        final Iterator iterator = array[n].iterator();
        while (iterator.hasNext()) {
            final PKIXPolicyNode pkixPolicyNode = (PKIXPolicyNode)iterator.next();
            if (pkixPolicyNode.getValidPolicy().equals(anObject)) {
                ((PKIXPolicyNode)pkixPolicyNode.getParent()).removeChild(pkixPolicyNode);
                iterator.remove();
                for (int i = n - 1; i >= 0; --i) {
                    final List list = array[i];
                    for (int j = 0; j < list.size(); ++j) {
                        final PKIXPolicyNode pkixPolicyNode2 = list.get(j);
                        if (!pkixPolicyNode2.hasChildren()) {
                            removePolicyNode = removePolicyNode(removePolicyNode, array, pkixPolicyNode2);
                            if (removePolicyNode == null) {
                                break;
                            }
                        }
                    }
                }
            }
        }
        return removePolicyNode;
    }
    
    protected static boolean isAnyPolicy(final Set set) {
        return set == null || set.contains("2.5.29.32.0") || set.isEmpty();
    }
    
    protected static Collection findCertificates(final X509CertStoreSelector selector, final List list) throws AnnotatedException {
        final HashSet set = new HashSet();
        final Iterator iterator = list.iterator();
        final CertificateFactory certificateFactory = new CertificateFactory();
        while (iterator.hasNext()) {
            final Object next = iterator.next();
            if (next instanceof Store) {
                final Store store = (Store)next;
                try {
                    for (final Object next2 : store.getMatches(selector)) {
                        if (next2 instanceof Encodable) {
                            set.add(certificateFactory.engineGenerateCertificate(new ByteArrayInputStream(((Encodable)next2).getEncoded())));
                        }
                        else {
                            if (!(next2 instanceof Certificate)) {
                                throw new AnnotatedException("Unknown object found in certificate store.");
                            }
                            set.add(next2);
                        }
                    }
                }
                catch (final StoreException ex) {
                    throw new AnnotatedException("Problem while picking certificates from X.509 store.", ex);
                }
                catch (final IOException ex2) {
                    throw new AnnotatedException("Problem while extracting certificates from X.509 store.", ex2);
                }
                catch (final CertificateException ex3) {
                    throw new AnnotatedException("Problem while extracting certificates from X.509 store.", ex3);
                }
            }
            else {
                final CertStore certStore = (CertStore)next;
                try {
                    set.addAll(certStore.getCertificates(selector));
                }
                catch (final CertStoreException ex4) {
                    throw new AnnotatedException("Problem while picking certificates from certificate store.", ex4);
                }
            }
        }
        return set;
    }
    
    protected static Collection findCertificates(final PKIXCertStoreSelector pkixCertStoreSelector, final List list) throws AnnotatedException {
        final HashSet set = new HashSet();
        for (final Object next : list) {
            if (next instanceof Store) {
                final Store store = (Store)next;
                try {
                    set.addAll(store.getMatches(pkixCertStoreSelector));
                }
                catch (final StoreException ex) {
                    throw new AnnotatedException("Problem while picking certificates from X.509 store.", ex);
                }
            }
            else {
                final CertStore certStore = (CertStore)next;
                try {
                    set.addAll(PKIXCertStoreSelector.getCertificates(pkixCertStoreSelector, certStore));
                }
                catch (final CertStoreException ex2) {
                    throw new AnnotatedException("Problem while picking certificates from certificate store.", ex2);
                }
            }
        }
        return set;
    }
    
    protected static Collection findCertificates(final X509AttributeCertStoreSelector x509AttributeCertStoreSelector, final List list) throws AnnotatedException {
        final HashSet set = new HashSet();
        for (final Object next : list) {
            if (next instanceof X509Store) {
                final X509Store x509Store = (X509Store)next;
                try {
                    set.addAll(x509Store.getMatches(x509AttributeCertStoreSelector));
                }
                catch (final StoreException ex) {
                    throw new AnnotatedException("Problem while picking certificates from X.509 store.", ex);
                }
            }
        }
        return set;
    }
    
    private static BigInteger getSerialNumber(final Object o) {
        if (o instanceof X509Certificate) {
            return ((X509Certificate)o).getSerialNumber();
        }
        return ((X509AttributeCertificate)o).getSerialNumber();
    }
    
    protected static void getCertStatus(final Date date, final X509CRL x509CRL, final Object o, final CertStatus certStatus) throws AnnotatedException {
        boolean indirectCRL;
        try {
            indirectCRL = isIndirectCRL(x509CRL);
        }
        catch (final CRLException ex) {
            throw new AnnotatedException("Failed check for indirect CRL.", ex);
        }
        X509CRLEntry x509CRLEntry;
        if (indirectCRL) {
            x509CRLEntry = x509CRL.getRevokedCertificate(getSerialNumber(o));
            if (x509CRLEntry == null) {
                return;
            }
            X500Principal o2 = x509CRLEntry.getCertificateIssuer();
            if (o2 == null) {
                o2 = getIssuerPrincipal(x509CRL);
            }
            if (!getEncodedIssuerPrincipal(o).equals(o2)) {
                return;
            }
        }
        else {
            if (!getEncodedIssuerPrincipal(o).equals(getIssuerPrincipal(x509CRL))) {
                return;
            }
            x509CRLEntry = x509CRL.getRevokedCertificate(getSerialNumber(o));
            if (x509CRLEntry == null) {
                return;
            }
        }
        ASN1Enumerated instance = null;
        if (x509CRLEntry.hasExtensions()) {
            try {
                instance = ASN1Enumerated.getInstance(getExtensionValue(x509CRLEntry, org.bouncycastle.asn1.x509.X509Extension.reasonCode.getId()));
            }
            catch (final Exception ex2) {
                throw new AnnotatedException("Reason code CRL entry extension could not be decoded.", ex2);
            }
        }
        final int certStatus2 = (null == instance) ? 0 : instance.intValueExact();
        if (date.getTime() >= x509CRLEntry.getRevocationDate().getTime() || certStatus2 == 0 || certStatus2 == 1 || certStatus2 == 2 || certStatus2 == 10) {
            certStatus.setCertStatus(certStatus2);
            certStatus.setRevocationDate(x509CRLEntry.getRevocationDate());
        }
    }
    
    protected static PublicKey getNextWorkingKey(final List list, final int n) throws CertPathValidatorException {
        final PublicKey publicKey = list.get(n).getPublicKey();
        if (!(publicKey instanceof DSAPublicKey)) {
            return publicKey;
        }
        final DSAPublicKey dsaPublicKey = (DSAPublicKey)publicKey;
        if (dsaPublicKey.getParams() != null) {
            return dsaPublicKey;
        }
        for (int i = n + 1; i < list.size(); ++i) {
            final PublicKey publicKey2 = list.get(i).getPublicKey();
            if (!(publicKey2 instanceof DSAPublicKey)) {
                throw new CertPathValidatorException("DSA parameters cannot be inherited from previous certificate.");
            }
            final DSAPublicKey dsaPublicKey2 = (DSAPublicKey)publicKey2;
            if (dsaPublicKey2.getParams() != null) {
                final DSAParams params = dsaPublicKey2.getParams();
                final DSAPublicKeySpec keySpec = new DSAPublicKeySpec(dsaPublicKey.getY(), params.getP(), params.getQ(), params.getG());
                try {
                    return KeyFactory.getInstance("DSA", "BC").generatePublic(keySpec);
                }
                catch (final Exception ex) {
                    throw new RuntimeException(ex.getMessage());
                }
            }
        }
        throw new CertPathValidatorException("DSA parameters cannot be inherited from previous certificate.");
    }
    
    protected static void verifyX509Certificate(final X509Certificate x509Certificate, final PublicKey publicKey, final String s) throws GeneralSecurityException {
        if (s == null) {
            x509Certificate.verify(publicKey);
        }
        else {
            x509Certificate.verify(publicKey, s);
        }
    }
    
    static boolean isIndirectCRL(final X509CRL x509CRL) throws CRLException {
        try {
            final byte[] extensionValue = x509CRL.getExtensionValue(Extension.issuingDistributionPoint.getId());
            return extensionValue != null && IssuingDistributionPoint.getInstance(ASN1OctetString.getInstance(extensionValue).getOctets()).isIndirectCRL();
        }
        catch (final Exception obj) {
            throw new CRLException("Exception reading IssuingDistributionPoint: " + obj);
        }
    }
    
    static {
        CERTIFICATE_POLICIES = Extension.certificatePolicies.getId();
        BASIC_CONSTRAINTS = Extension.basicConstraints.getId();
        POLICY_MAPPINGS = Extension.policyMappings.getId();
        SUBJECT_ALTERNATIVE_NAME = Extension.subjectAlternativeName.getId();
        NAME_CONSTRAINTS = Extension.nameConstraints.getId();
        KEY_USAGE = Extension.keyUsage.getId();
        INHIBIT_ANY_POLICY = Extension.inhibitAnyPolicy.getId();
        ISSUING_DISTRIBUTION_POINT = Extension.issuingDistributionPoint.getId();
        DELTA_CRL_INDICATOR = Extension.deltaCRLIndicator.getId();
        POLICY_CONSTRAINTS = Extension.policyConstraints.getId();
        CRL_NUMBER = Extension.cRLNumber.getId();
        crlReasons = new String[] { "unspecified", "keyCompromise", "cACompromise", "affiliationChanged", "superseded", "cessationOfOperation", "certificateHold", "unknown", "removeFromCRL", "privilegeWithdrawn", "aACompromise" };
    }
}
