Search in sources :

Example 1 with ExtendedPKIXParameters

use of com.github.zhenwei.provider.x509.ExtendedPKIXParameters in project XobotOS by xamarin.

the class RFC3280CertPathUtilities method processCRLF.

/**
     * Obtain and validate the certification path for the complete CRL issuer.
     * If a key usage extension is present in the CRL issuer's certificate,
     * verify that the cRLSign bit is set.
     *
     * @param crl                CRL which contains revocation information for the certificate
     *                           <code>cert</code>.
     * @param cert               The attribute certificate or certificate to check if it is
     *                           revoked.
     * @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>.
     * @param defaultCRLSignKey  The public key of the issuer certificate
     *                           <code>defaultCRLSignCert</code>.
     * @param paramsPKIX         paramsPKIX PKIX parameters.
     * @param certPathCerts      The certificates on the certification path.
     * @return A <code>Set</code> with all keys of possible CRL issuer
     *         certificates.
     * @throws AnnotatedException if the CRL is not valid or the status cannot be checked or
     *                            some error occurs.
     */
protected static Set processCRLF(X509CRL crl, Object cert, X509Certificate defaultCRLSignCert, PublicKey defaultCRLSignKey, ExtendedPKIXParameters paramsPKIX, List certPathCerts) throws AnnotatedException {
    // (f)
    // get issuer from CRL
    X509CertStoreSelector selector = new X509CertStoreSelector();
    try {
        byte[] issuerPrincipal = CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded();
        selector.setSubject(issuerPrincipal);
    } catch (IOException e) {
        throw new AnnotatedException("Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e);
    }
    // get CRL signing certs
    Collection coll;
    try {
        coll = CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getStores());
        coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getAdditionalStores()));
        coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getCertStores()));
    } catch (AnnotatedException e) {
        throw new AnnotatedException("Issuer certificate for CRL cannot be searched.", e);
    }
    coll.add(defaultCRLSignCert);
    Iterator cert_it = coll.iterator();
    List validCerts = new ArrayList();
    List validKeys = new ArrayList();
    while (cert_it.hasNext()) {
        X509Certificate signingCert = (X509Certificate) cert_it.next();
        /*
             * CA of the certificate, for which this CRL is checked, has also
             * signed CRL, so skip the path validation, because is already done
             */
        if (signingCert.equals(defaultCRLSignCert)) {
            validCerts.add(signingCert);
            validKeys.add(defaultCRLSignKey);
            continue;
        }
        try {
            CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
            selector = new X509CertStoreSelector();
            selector.setCertificate(signingCert);
            ExtendedPKIXParameters temp = (ExtendedPKIXParameters) paramsPKIX.clone();
            temp.setTargetCertConstraints(selector);
            ExtendedPKIXBuilderParameters params = (ExtendedPKIXBuilderParameters) ExtendedPKIXBuilderParameters.getInstance(temp);
            /*
                 * if signingCert is placed not higher on the cert path a
                 * dependency loop results. CRL for cert is checked, but
                 * signingCert is needed for checking the CRL which is dependent
                 * on checking cert because it is higher in the cert path and so
                 * signing signingCert transitively. so, revocation is disabled,
                 * forgery attacks of the CRL are detected in this outer loop
                 * for all other it must be enabled to prevent forgery attacks
                 */
            if (certPathCerts.contains(signingCert)) {
                params.setRevocationEnabled(false);
            } else {
                params.setRevocationEnabled(true);
            }
            List certs = builder.build(params).getCertPath().getCertificates();
            validCerts.add(signingCert);
            validKeys.add(CertPathValidatorUtilities.getNextWorkingKey(certs, 0));
        } catch (CertPathBuilderException e) {
            throw new AnnotatedException("Internal error.", e);
        } catch (CertPathValidatorException e) {
            throw new AnnotatedException("Public key of issuer certificate of CRL could not be retrieved.", e);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
    Set checkKeys = new HashSet();
    AnnotatedException lastException = null;
    for (int i = 0; i < validCerts.size(); i++) {
        X509Certificate signCert = (X509Certificate) validCerts.get(i);
        boolean[] keyusage = signCert.getKeyUsage();
        if (keyusage != null && (keyusage.length < 7 || !keyusage[CRL_SIGN])) {
            lastException = new AnnotatedException("Issuer certificate key usage extension does not permit CRL signing.");
        } else {
            checkKeys.add(validKeys.get(i));
        }
    }
    if (checkKeys.isEmpty() && lastException == null) {
        throw new AnnotatedException("Cannot find a valid issuer certificate.");
    }
    if (checkKeys.isEmpty() && lastException != null) {
        throw lastException;
    }
    return checkKeys;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ExtendedPKIXBuilderParameters(org.bouncycastle.x509.ExtendedPKIXBuilderParameters) X509CertStoreSelector(org.bouncycastle.x509.X509CertStoreSelector) ArrayList(java.util.ArrayList) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertPathBuilderException(java.security.cert.CertPathBuilderException) IOException(java.io.IOException) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) ExtendedPKIXParameters(org.bouncycastle.x509.ExtendedPKIXParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) Iterator(java.util.Iterator) Collection(java.util.Collection) List(java.util.List) ArrayList(java.util.ArrayList) CertPathBuilder(java.security.cert.CertPathBuilder) HashSet(java.util.HashSet)

Example 2 with ExtendedPKIXParameters

use of com.github.zhenwei.provider.x509.ExtendedPKIXParameters in project robovm by robovm.

the class RFC3280CertPathUtilities method processCRLF.

/**
     * Obtain and validate the certification path for the complete CRL issuer.
     * If a key usage extension is present in the CRL issuer's certificate,
     * verify that the cRLSign bit is set.
     *
     * @param crl                CRL which contains revocation information for the certificate
     *                           <code>cert</code>.
     * @param cert               The attribute certificate or certificate to check if it is
     *                           revoked.
     * @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>.
     * @param defaultCRLSignKey  The public key of the issuer certificate
     *                           <code>defaultCRLSignCert</code>.
     * @param paramsPKIX         paramsPKIX PKIX parameters.
     * @param certPathCerts      The certificates on the certification path.
     * @return A <code>Set</code> with all keys of possible CRL issuer
     *         certificates.
     * @throws AnnotatedException if the CRL is not valid or the status cannot be checked or
     *                            some error occurs.
     */
protected static Set processCRLF(X509CRL crl, Object cert, X509Certificate defaultCRLSignCert, PublicKey defaultCRLSignKey, ExtendedPKIXParameters paramsPKIX, List certPathCerts) throws AnnotatedException {
    // (f)
    // get issuer from CRL
    X509CertStoreSelector selector = new X509CertStoreSelector();
    try {
        byte[] issuerPrincipal = CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded();
        selector.setSubject(issuerPrincipal);
    } catch (IOException e) {
        throw new AnnotatedException("Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e);
    }
    // get CRL signing certs
    Collection coll;
    try {
        coll = CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getStores());
        coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getAdditionalStores()));
        coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getCertStores()));
    } catch (AnnotatedException e) {
        throw new AnnotatedException("Issuer certificate for CRL cannot be searched.", e);
    }
    coll.add(defaultCRLSignCert);
    Iterator cert_it = coll.iterator();
    List validCerts = new ArrayList();
    List validKeys = new ArrayList();
    while (cert_it.hasNext()) {
        X509Certificate signingCert = (X509Certificate) cert_it.next();
        /*
             * CA of the certificate, for which this CRL is checked, has also
             * signed CRL, so skip the path validation, because is already done
             */
        if (signingCert.equals(defaultCRLSignCert)) {
            validCerts.add(signingCert);
            validKeys.add(defaultCRLSignKey);
            continue;
        }
        try {
            CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
            selector = new X509CertStoreSelector();
            selector.setCertificate(signingCert);
            ExtendedPKIXParameters temp = (ExtendedPKIXParameters) paramsPKIX.clone();
            temp.setTargetCertConstraints(selector);
            ExtendedPKIXBuilderParameters params = (ExtendedPKIXBuilderParameters) ExtendedPKIXBuilderParameters.getInstance(temp);
            /*
                 * if signingCert is placed not higher on the cert path a
                 * dependency loop results. CRL for cert is checked, but
                 * signingCert is needed for checking the CRL which is dependent
                 * on checking cert because it is higher in the cert path and so
                 * signing signingCert transitively. so, revocation is disabled,
                 * forgery attacks of the CRL are detected in this outer loop
                 * for all other it must be enabled to prevent forgery attacks
                 */
            if (certPathCerts.contains(signingCert)) {
                params.setRevocationEnabled(false);
            } else {
                params.setRevocationEnabled(true);
            }
            List certs = builder.build(params).getCertPath().getCertificates();
            validCerts.add(signingCert);
            validKeys.add(CertPathValidatorUtilities.getNextWorkingKey(certs, 0));
        } catch (CertPathBuilderException e) {
            throw new AnnotatedException("Internal error.", e);
        } catch (CertPathValidatorException e) {
            throw new AnnotatedException("Public key of issuer certificate of CRL could not be retrieved.", e);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
    Set checkKeys = new HashSet();
    AnnotatedException lastException = null;
    for (int i = 0; i < validCerts.size(); i++) {
        X509Certificate signCert = (X509Certificate) validCerts.get(i);
        boolean[] keyusage = signCert.getKeyUsage();
        if (keyusage != null && (keyusage.length < 7 || !keyusage[CRL_SIGN])) {
            lastException = new AnnotatedException("Issuer certificate key usage extension does not permit CRL signing.");
        } else {
            checkKeys.add(validKeys.get(i));
        }
    }
    if (checkKeys.isEmpty() && lastException == null) {
        throw new AnnotatedException("Cannot find a valid issuer certificate.");
    }
    if (checkKeys.isEmpty() && lastException != null) {
        throw lastException;
    }
    return checkKeys;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ExtendedPKIXBuilderParameters(org.bouncycastle.x509.ExtendedPKIXBuilderParameters) X509CertStoreSelector(org.bouncycastle.x509.X509CertStoreSelector) ArrayList(java.util.ArrayList) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertPathBuilderException(java.security.cert.CertPathBuilderException) IOException(java.io.IOException) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) ExtendedPKIXParameters(org.bouncycastle.x509.ExtendedPKIXParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) Iterator(java.util.Iterator) Collection(java.util.Collection) List(java.util.List) ArrayList(java.util.ArrayList) CertPathBuilder(java.security.cert.CertPathBuilder) HashSet(java.util.HashSet)

Example 3 with ExtendedPKIXParameters

use of com.github.zhenwei.provider.x509.ExtendedPKIXParameters in project robovm by robovm.

the class PKIXCertPathValidatorSpi method engineValidate.

// END android-added
public CertPathValidatorResult engineValidate(CertPath certPath, CertPathParameters params) throws CertPathValidatorException, InvalidAlgorithmParameterException {
    if (!(params instanceof PKIXParameters)) {
        throw new InvalidAlgorithmParameterException("Parameters must be a " + PKIXParameters.class.getName() + " instance.");
    }
    ExtendedPKIXParameters paramsPKIX;
    if (params instanceof ExtendedPKIXParameters) {
        paramsPKIX = (ExtendedPKIXParameters) params;
    } else {
        paramsPKIX = ExtendedPKIXParameters.getInstance((PKIXParameters) params);
    }
    if (paramsPKIX.getTrustAnchors() == null) {
        throw new InvalidAlgorithmParameterException("trustAnchors is null, this is not allowed for certification path validation.");
    }
    //
    // 6.1.1 - inputs
    //
    //
    // (a)
    //
    List certs = certPath.getCertificates();
    int n = certs.size();
    if (certs.isEmpty()) {
        throw new CertPathValidatorException("Certification path is empty.", null, certPath, 0);
    }
    // BEGIN android-added
    {
        X509Certificate cert = (X509Certificate) certs.get(0);
        if (cert != null) {
            BigInteger serial = cert.getSerialNumber();
            if (blacklist.isSerialNumberBlackListed(serial)) {
                // emulate CRL exception message in RFC3280CertPathUtilities.checkCRLs
                String message = "Certificate revocation of serial 0x" + serial.toString(16);
                System.out.println(message);
                AnnotatedException e = new AnnotatedException(message);
                throw new CertPathValidatorException(e.getMessage(), e, certPath, 0);
            }
        }
    }
    // END android-added
    //
    // (b)
    //
    // Date validDate = CertPathValidatorUtilities.getValidDate(paramsPKIX);
    //
    // (c)
    //
    Set userInitialPolicySet = paramsPKIX.getInitialPolicies();
    //
    // (d)
    // 
    TrustAnchor trust;
    try {
        trust = CertPathValidatorUtilities.findTrustAnchor((X509Certificate) certs.get(certs.size() - 1), paramsPKIX.getTrustAnchors(), paramsPKIX.getSigProvider());
    } catch (AnnotatedException e) {
        throw new CertPathValidatorException(e.getMessage(), e, certPath, certs.size() - 1);
    }
    if (trust == null) {
        throw new CertPathValidatorException("Trust anchor for certification path not found.", null, certPath, -1);
    }
    //
    // (e), (f), (g) are part of the paramsPKIX object.
    //
    Iterator certIter;
    int index = 0;
    int i;
    // Certificate for each interation of the validation loop
    // Signature information for each iteration of the validation loop
    //
    // 6.1.2 - setup
    //
    //
    // (a)
    //
    List[] policyNodes = new ArrayList[n + 1];
    for (int j = 0; j < policyNodes.length; j++) {
        policyNodes[j] = new ArrayList();
    }
    Set policySet = new HashSet();
    policySet.add(RFC3280CertPathUtilities.ANY_POLICY);
    PKIXPolicyNode validPolicyTree = new PKIXPolicyNode(new ArrayList(), 0, policySet, null, new HashSet(), RFC3280CertPathUtilities.ANY_POLICY, false);
    policyNodes[0].add(validPolicyTree);
    //
    // (b) and (c)
    //
    PKIXNameConstraintValidator nameConstraintValidator = new PKIXNameConstraintValidator();
    // (d)
    //
    int explicitPolicy;
    Set acceptablePolicies = new HashSet();
    if (paramsPKIX.isExplicitPolicyRequired()) {
        explicitPolicy = 0;
    } else {
        explicitPolicy = n + 1;
    }
    //
    // (e)
    //
    int inhibitAnyPolicy;
    if (paramsPKIX.isAnyPolicyInhibited()) {
        inhibitAnyPolicy = 0;
    } else {
        inhibitAnyPolicy = n + 1;
    }
    //
    // (f)
    //
    int policyMapping;
    if (paramsPKIX.isPolicyMappingInhibited()) {
        policyMapping = 0;
    } else {
        policyMapping = n + 1;
    }
    //
    // (g), (h), (i), (j)
    //
    PublicKey workingPublicKey;
    X500Principal workingIssuerName;
    X509Certificate sign = trust.getTrustedCert();
    try {
        if (sign != null) {
            workingIssuerName = CertPathValidatorUtilities.getSubjectPrincipal(sign);
            workingPublicKey = sign.getPublicKey();
        } else {
            workingIssuerName = new X500Principal(trust.getCAName());
            workingPublicKey = trust.getCAPublicKey();
        }
    } catch (IllegalArgumentException ex) {
        throw new ExtCertPathValidatorException("Subject of trust anchor could not be (re)encoded.", ex, certPath, -1);
    }
    AlgorithmIdentifier workingAlgId = null;
    try {
        workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey);
    } catch (CertPathValidatorException e) {
        throw new ExtCertPathValidatorException("Algorithm identifier of public key of trust anchor could not be read.", e, certPath, -1);
    }
    DERObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.getObjectId();
    ASN1Encodable workingPublicKeyParameters = workingAlgId.getParameters();
    //
    // (k)
    //
    int maxPathLength = n;
    if (paramsPKIX.getTargetConstraints() != null && !paramsPKIX.getTargetConstraints().match((X509Certificate) certs.get(0))) {
        throw new ExtCertPathValidatorException("Target certificate in certification path does not match targetConstraints.", null, certPath, 0);
    }
    // 
    // initialize CertPathChecker's
    //
    List pathCheckers = paramsPKIX.getCertPathCheckers();
    certIter = pathCheckers.iterator();
    while (certIter.hasNext()) {
        ((PKIXCertPathChecker) certIter.next()).init(false);
    }
    X509Certificate cert = null;
    for (index = certs.size() - 1; index >= 0; index--) {
        // BEGIN android-added
        if (blacklist.isPublicKeyBlackListed(workingPublicKey)) {
            // emulate CRL exception message in RFC3280CertPathUtilities.checkCRLs
            String message = "Certificate revocation of public key " + workingPublicKey;
            System.out.println(message);
            AnnotatedException e = new AnnotatedException(message);
            throw new CertPathValidatorException(e.getMessage(), e, certPath, index);
        }
        // END android-added
        // try
        // {
        //
        // i as defined in the algorithm description
        //
        i = n - index;
        //
        // set certificate to be checked in this round
        // sign and workingPublicKey and workingIssuerName are set
        // at the end of the for loop and initialized the
        // first time from the TrustAnchor
        //
        cert = (X509Certificate) certs.get(index);
        boolean verificationAlreadyPerformed = (index == certs.size() - 1);
        //
        // 6.1.3
        //
        RFC3280CertPathUtilities.processCertA(certPath, paramsPKIX, index, workingPublicKey, verificationAlreadyPerformed, workingIssuerName, sign);
        RFC3280CertPathUtilities.processCertBC(certPath, index, nameConstraintValidator);
        validPolicyTree = RFC3280CertPathUtilities.processCertD(certPath, index, acceptablePolicies, validPolicyTree, policyNodes, inhibitAnyPolicy);
        validPolicyTree = RFC3280CertPathUtilities.processCertE(certPath, index, validPolicyTree);
        RFC3280CertPathUtilities.processCertF(certPath, index, validPolicyTree, explicitPolicy);
        if (i != n) {
            if (cert != null && cert.getVersion() == 1) {
                throw new CertPathValidatorException("Version 1 certificates can't be used as CA ones.", null, certPath, index);
            }
            RFC3280CertPathUtilities.prepareNextCertA(certPath, index);
            validPolicyTree = RFC3280CertPathUtilities.prepareCertB(certPath, index, policyNodes, validPolicyTree, policyMapping);
            RFC3280CertPathUtilities.prepareNextCertG(certPath, index, nameConstraintValidator);
            // (h)
            explicitPolicy = RFC3280CertPathUtilities.prepareNextCertH1(certPath, index, explicitPolicy);
            policyMapping = RFC3280CertPathUtilities.prepareNextCertH2(certPath, index, policyMapping);
            inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertH3(certPath, index, inhibitAnyPolicy);
            //
            // (i)
            //
            explicitPolicy = RFC3280CertPathUtilities.prepareNextCertI1(certPath, index, explicitPolicy);
            policyMapping = RFC3280CertPathUtilities.prepareNextCertI2(certPath, index, policyMapping);
            // (j)
            inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertJ(certPath, index, inhibitAnyPolicy);
            // (k)
            RFC3280CertPathUtilities.prepareNextCertK(certPath, index);
            // (l)
            maxPathLength = RFC3280CertPathUtilities.prepareNextCertL(certPath, index, maxPathLength);
            // (m)
            maxPathLength = RFC3280CertPathUtilities.prepareNextCertM(certPath, index, maxPathLength);
            // (n)
            RFC3280CertPathUtilities.prepareNextCertN(certPath, index);
            Set criticalExtensions = cert.getCriticalExtensionOIDs();
            if (criticalExtensions != null) {
                criticalExtensions = new HashSet(criticalExtensions);
                // these extensions are handled by the algorithm
                criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE);
                criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
                criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS);
                criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY);
                criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT);
                criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR);
                criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS);
                criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS);
                criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME);
                criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS);
            } else {
                criticalExtensions = new HashSet();
            }
            // (o)
            RFC3280CertPathUtilities.prepareNextCertO(certPath, index, criticalExtensions, pathCheckers);
            // set signing certificate for next round
            sign = cert;
            // (c)
            workingIssuerName = CertPathValidatorUtilities.getSubjectPrincipal(sign);
            // (d)
            try {
                workingPublicKey = CertPathValidatorUtilities.getNextWorkingKey(certPath.getCertificates(), index);
            } catch (CertPathValidatorException e) {
                throw new CertPathValidatorException("Next working key could not be retrieved.", e, certPath, index);
            }
            workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey);
            // (f)
            workingPublicKeyAlgorithm = workingAlgId.getObjectId();
            // (e)
            workingPublicKeyParameters = workingAlgId.getParameters();
        }
    }
    //
    // 6.1.5 Wrap-up procedure
    //
    explicitPolicy = RFC3280CertPathUtilities.wrapupCertA(explicitPolicy, cert);
    explicitPolicy = RFC3280CertPathUtilities.wrapupCertB(certPath, index + 1, explicitPolicy);
    //
    // (c) (d) and (e) are already done
    //
    //
    // (f)
    //
    Set criticalExtensions = cert.getCriticalExtensionOIDs();
    if (criticalExtensions != null) {
        criticalExtensions = new HashSet(criticalExtensions);
        // these extensions are handled by the algorithm
        criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE);
        criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
        criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS);
        criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY);
        criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT);
        criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR);
        criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS);
        criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS);
        criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME);
        criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS);
        criticalExtensions.remove(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS);
    } else {
        criticalExtensions = new HashSet();
    }
    RFC3280CertPathUtilities.wrapupCertF(certPath, index + 1, pathCheckers, criticalExtensions);
    PKIXPolicyNode intersection = RFC3280CertPathUtilities.wrapupCertG(certPath, paramsPKIX, userInitialPolicySet, index + 1, policyNodes, validPolicyTree, acceptablePolicies);
    if ((explicitPolicy > 0) || (intersection != null)) {
        return new PKIXCertPathValidatorResult(trust, intersection, cert.getPublicKey());
    }
    throw new CertPathValidatorException("Path processing failed on policy.", null, certPath, index);
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ArrayList(java.util.ArrayList) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) ExtendedPKIXParameters(org.bouncycastle.x509.ExtendedPKIXParameters) PKIXParameters(java.security.cert.PKIXParameters) PKIXCertPathChecker(java.security.cert.PKIXCertPathChecker) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) HashSet(java.util.HashSet) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PublicKey(java.security.PublicKey) TrustAnchor(java.security.cert.TrustAnchor) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) X509Certificate(java.security.cert.X509Certificate) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) ExtendedPKIXParameters(org.bouncycastle.x509.ExtendedPKIXParameters) PKIXCertPathValidatorResult(java.security.cert.PKIXCertPathValidatorResult) BigInteger(java.math.BigInteger) X500Principal(javax.security.auth.x500.X500Principal)

Example 4 with ExtendedPKIXParameters

use of com.github.zhenwei.provider.x509.ExtendedPKIXParameters in project LinLong-Java by zhenwei1108.

the class PKIXAttrCertPathBuilderSpi method engineBuild.

/**
 * Build and validate a CertPath using the given parameter.
 *
 * @param params PKIXBuilderParameters object containing all information to build the CertPath
 */
public CertPathBuilderResult engineBuild(CertPathParameters params) throws CertPathBuilderException, InvalidAlgorithmParameterException {
    if (!(params instanceof PKIXBuilderParameters) && !(params instanceof ExtendedPKIXBuilderParameters) && !(params instanceof PKIXExtendedBuilderParameters)) {
        throw new InvalidAlgorithmParameterException("Parameters must be an instance of " + PKIXBuilderParameters.class.getName() + " or " + PKIXExtendedBuilderParameters.class.getName() + ".");
    }
    List targetStores = new ArrayList();
    PKIXExtendedBuilderParameters paramsPKIX;
    if (params instanceof PKIXBuilderParameters) {
        PKIXExtendedBuilderParameters.Builder paramsPKIXBldr = new PKIXExtendedBuilderParameters.Builder((PKIXBuilderParameters) params);
        if (params instanceof ExtendedPKIXParameters) {
            ExtendedPKIXBuilderParameters extPKIX = (ExtendedPKIXBuilderParameters) params;
            paramsPKIXBldr.addExcludedCerts(extPKIX.getExcludedCerts());
            paramsPKIXBldr.setMaxPathLength(extPKIX.getMaxPathLength());
            targetStores = extPKIX.getStores();
        }
        paramsPKIX = paramsPKIXBldr.build();
    } else {
        paramsPKIX = (PKIXExtendedBuilderParameters) params;
    }
    Collection targets;
    Iterator targetIter;
    List certPathList = new ArrayList();
    X509AttributeCertificate cert;
    // search target certificates
    PKIXExtendedParameters baseParams = paramsPKIX.getBaseParameters();
    Selector certSelect = baseParams.getTargetConstraints();
    if (!(certSelect instanceof X509AttributeCertStoreSelector)) {
        throw new CertPathBuilderException("TargetConstraints must be an instance of " + X509AttributeCertStoreSelector.class.getName() + " for " + this.getClass().getName() + " class.");
    }
    try {
        targets = findCertificates((X509AttributeCertStoreSelector) certSelect, targetStores);
    } catch (AnnotatedException e) {
        throw new ExtCertPathBuilderException("Error finding target attribute certificate.", e);
    }
    if (targets.isEmpty()) {
        throw new CertPathBuilderException("No attribute certificate found matching targetConstraints.");
    }
    CertPathBuilderResult result = null;
    // check all potential target certificates
    targetIter = targets.iterator();
    while (targetIter.hasNext() && result == null) {
        cert = (X509AttributeCertificate) targetIter.next();
        X509CertStoreSelector selector = new X509CertStoreSelector();
        Principal[] principals = cert.getIssuer().getPrincipals();
        LinkedHashSet issuers = new LinkedHashSet();
        for (int i = 0; i < principals.length; i++) {
            try {
                if (principals[i] instanceof X500Principal) {
                    selector.setSubject(((X500Principal) principals[i]).getEncoded());
                }
                PKIXCertStoreSelector certStoreSelector = new PKIXCertStoreSelector.Builder(selector).build();
                CertPathValidatorUtilities.findCertificates(issuers, certStoreSelector, baseParams.getCertStores());
                CertPathValidatorUtilities.findCertificates(issuers, certStoreSelector, baseParams.getCertificateStores());
            } catch (AnnotatedException e) {
                throw new ExtCertPathBuilderException("Public key certificate for attribute certificate cannot be searched.", e);
            } catch (IOException e) {
                throw new ExtCertPathBuilderException("cannot encode X500Principal.", e);
            }
        }
        if (issuers.isEmpty()) {
            throw new CertPathBuilderException("Public key certificate for attribute certificate cannot be found.");
        }
        Iterator it = issuers.iterator();
        while (it.hasNext() && result == null) {
            result = build(cert, (X509Certificate) it.next(), paramsPKIX, certPathList);
        }
    }
    if (result == null && certPathException != null) {
        throw new ExtCertPathBuilderException("Possible certificate chain could not be validated.", certPathException);
    }
    if (result == null && certPathException == null) {
        throw new CertPathBuilderException("Unable to find certificate chain.");
    }
    return result;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ExtendedPKIXBuilderParameters(com.github.zhenwei.provider.x509.ExtendedPKIXBuilderParameters) CertPathBuilderResult(java.security.cert.CertPathBuilderResult) PKIXCertPathBuilderResult(java.security.cert.PKIXCertPathBuilderResult) ArrayList(java.util.ArrayList) X509AttributeCertificate(com.github.zhenwei.provider.x509.X509AttributeCertificate) PKIXExtendedBuilderParameters(com.github.zhenwei.provider.jcajce.PKIXExtendedBuilderParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) ExtCertPathBuilderException(com.github.zhenwei.provider.jce.exception.ExtCertPathBuilderException) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) X509AttributeCertStoreSelector(com.github.zhenwei.provider.x509.X509AttributeCertStoreSelector) Selector(com.github.zhenwei.core.util.Selector) PKIXCertStoreSelector(com.github.zhenwei.provider.jcajce.PKIXCertStoreSelector) X509CertStoreSelector(com.github.zhenwei.provider.x509.X509CertStoreSelector) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) ExtendedPKIXBuilderParameters(com.github.zhenwei.provider.x509.ExtendedPKIXBuilderParameters) PKIXBuilderParameters(java.security.cert.PKIXBuilderParameters) X509CertStoreSelector(com.github.zhenwei.provider.x509.X509CertStoreSelector) X509AttributeCertStoreSelector(com.github.zhenwei.provider.x509.X509AttributeCertStoreSelector) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) PKIXCertStoreSelector(com.github.zhenwei.provider.jcajce.PKIXCertStoreSelector) PKIXExtendedParameters(com.github.zhenwei.provider.jcajce.PKIXExtendedParameters) ExtendedPKIXParameters(com.github.zhenwei.provider.x509.ExtendedPKIXParameters) ExtCertPathBuilderException(com.github.zhenwei.provider.jce.exception.ExtCertPathBuilderException) Collection(java.util.Collection) X500Principal(javax.security.auth.x500.X500Principal) X500Principal(javax.security.auth.x500.X500Principal) Principal(java.security.Principal)

Example 5 with ExtendedPKIXParameters

use of com.github.zhenwei.provider.x509.ExtendedPKIXParameters in project LinLong-Java by zhenwei1108.

the class PKIXAttrCertPathValidatorSpi method engineValidate.

/**
 * Validates an attribute certificate with the given certificate path.
 *
 * <p>
 * <code>params</code> must be an instance of
 * <code>ExtendedPKIXParameters</code>.
 * <p>
 * The target constraints in the <code>params</code> must be an
 * <code>X509AttributeCertStoreSelector</code> with at least the attribute
 * certificate criterion set. Obey that also target informations may be necessary to correctly
 * validate this attribute certificate.
 * <p>
 * The attribute certificate issuer must be added to the trusted attribute issuers with {@link
 * com.github.zhenwei.provider.x509.ExtendedPKIXParameters#setTrustedACIssuers(Set)}.
 *
 * @param certPath The certificate path which belongs to the attribute certificate issuer public
 *                 key certificate.
 * @param params   The PKIX parameters.
 * @return A <code>PKIXCertPathValidatorResult</code> of the result of validating the
 * <code>certPath</code>.
 * @throws InvalidAlgorithmParameterException if <code>params</code> is inappropriate for this
 *                                            validator.
 * @throws CertPathValidatorException         if the verification fails.
 */
public CertPathValidatorResult engineValidate(CertPath certPath, CertPathParameters params) throws CertPathValidatorException, InvalidAlgorithmParameterException {
    if (!(params instanceof ExtendedPKIXParameters || params instanceof PKIXExtendedParameters)) {
        throw new InvalidAlgorithmParameterException("Parameters must be a " + ExtendedPKIXParameters.class.getName() + " instance.");
    }
    Set attrCertCheckers = new HashSet();
    Set prohibitedACAttrbiutes = new HashSet();
    Set necessaryACAttributes = new HashSet();
    Set trustedACIssuers = new HashSet();
    PKIXExtendedParameters paramsPKIX;
    if (params instanceof PKIXParameters) {
        PKIXExtendedParameters.Builder paramsPKIXBldr = new PKIXExtendedParameters.Builder((PKIXParameters) params);
        if (params instanceof ExtendedPKIXParameters) {
            ExtendedPKIXParameters extPKIX = (ExtendedPKIXParameters) params;
            paramsPKIXBldr.setUseDeltasEnabled(extPKIX.isUseDeltasEnabled());
            paramsPKIXBldr.setValidityModel(extPKIX.getValidityModel());
            attrCertCheckers = extPKIX.getAttrCertCheckers();
            prohibitedACAttrbiutes = extPKIX.getProhibitedACAttributes();
            necessaryACAttributes = extPKIX.getNecessaryACAttributes();
        }
        paramsPKIX = paramsPKIXBldr.build();
    } else {
        paramsPKIX = (PKIXExtendedParameters) params;
    }
    final Date currentDate = new Date();
    final Date validityDate = CertPathValidatorUtilities.getValidityDate(paramsPKIX, currentDate);
    Selector certSelect = paramsPKIX.getTargetConstraints();
    if (!(certSelect instanceof X509AttributeCertStoreSelector)) {
        throw new InvalidAlgorithmParameterException("TargetConstraints must be an instance of " + X509AttributeCertStoreSelector.class.getName() + " for " + this.getClass().getName() + " class.");
    }
    X509AttributeCertificate attrCert = ((X509AttributeCertStoreSelector) certSelect).getAttributeCert();
    CertPath holderCertPath = RFC3281CertPathUtilities.processAttrCert1(attrCert, paramsPKIX);
    CertPathValidatorResult result = RFC3281CertPathUtilities.processAttrCert2(certPath, paramsPKIX);
    X509Certificate issuerCert = (X509Certificate) certPath.getCertificates().get(0);
    RFC3281CertPathUtilities.processAttrCert3(issuerCert, paramsPKIX);
    RFC3281CertPathUtilities.processAttrCert4(issuerCert, trustedACIssuers);
    RFC3281CertPathUtilities.processAttrCert5(attrCert, validityDate);
    // 6 already done in X509AttributeCertStoreSelector
    RFC3281CertPathUtilities.processAttrCert7(attrCert, certPath, holderCertPath, paramsPKIX, attrCertCheckers);
    RFC3281CertPathUtilities.additionalChecks(attrCert, prohibitedACAttrbiutes, necessaryACAttributes);
    RFC3281CertPathUtilities.checkCRLs(attrCert, paramsPKIX, currentDate, validityDate, issuerCert, certPath.getCertificates(), helper);
    return result;
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) Set(java.util.Set) HashSet(java.util.HashSet) X509AttributeCertStoreSelector(com.github.zhenwei.provider.x509.X509AttributeCertStoreSelector) X509AttributeCertificate(com.github.zhenwei.provider.x509.X509AttributeCertificate) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) PKIXExtendedParameters(com.github.zhenwei.provider.jcajce.PKIXExtendedParameters) ExtendedPKIXParameters(com.github.zhenwei.provider.x509.ExtendedPKIXParameters) ExtendedPKIXParameters(com.github.zhenwei.provider.x509.ExtendedPKIXParameters) PKIXParameters(java.security.cert.PKIXParameters) CertPath(java.security.cert.CertPath) CertPathValidatorResult(java.security.cert.CertPathValidatorResult) HashSet(java.util.HashSet) X509AttributeCertStoreSelector(com.github.zhenwei.provider.x509.X509AttributeCertStoreSelector) Selector(com.github.zhenwei.core.util.Selector)

Aggregations

X509Certificate (java.security.cert.X509Certificate)10 ArrayList (java.util.ArrayList)9 Iterator (java.util.Iterator)9 List (java.util.List)9 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)8 CertPathValidatorException (java.security.cert.CertPathValidatorException)8 CertPathBuilderException (java.security.cert.CertPathBuilderException)7 HashSet (java.util.HashSet)7 Set (java.util.Set)7 PKIXExtendedParameters (com.github.zhenwei.provider.jcajce.PKIXExtendedParameters)6 ExtendedPKIXParameters (com.github.zhenwei.provider.x509.ExtendedPKIXParameters)6 ExtCertPathValidatorException (org.bouncycastle.jce.exception.ExtCertPathValidatorException)6 ExtendedPKIXParameters (org.bouncycastle.x509.ExtendedPKIXParameters)6 PKIXExtendedBuilderParameters (com.github.zhenwei.provider.jcajce.PKIXExtendedBuilderParameters)5 IOException (java.io.IOException)5 PKIXParameters (java.security.cert.PKIXParameters)5 GeneralSecurityException (java.security.GeneralSecurityException)4 PublicKey (java.security.PublicKey)4 CertificateExpiredException (java.security.cert.CertificateExpiredException)4 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)4