Search in sources :

Example 96 with X509CertSelector

use of java.security.cert.X509CertSelector in project robovm by robovm.

the class PKIXBuilderParametersTest method testSetMaxPathLength.

/**
     * Test for <code>setMaxPathLength()</code>
     */
public final void testSetMaxPathLength() throws Exception {
    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());
    keyTest.load(null, null);
    ByteArrayInputStream certArray = new ByteArrayInputStream(certificate.getBytes());
    ByteArrayInputStream certArray2 = new ByteArrayInputStream(certificate2.getBytes());
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate[] cert = new X509Certificate[2];
    cert[0] = (X509Certificate) cf.generateCertificate(certArray);
    cert[1] = (X509Certificate) cf.generateCertificate(certArray2);
    keyTest.setCertificateEntry("alias1", cert[0]);
    keyTest.setCertificateEntry("alias2", cert[0]);
    keyTest.setCertificateEntry("alias3", cert[1]);
    PKIXBuilderParameters p = new PKIXBuilderParameters(keyTest, new X509CertSelector());
    assertEquals(5, p.getMaxPathLength());
    p.setMaxPathLength(10);
    assertEquals(10, p.getMaxPathLength());
    p.setMaxPathLength(0);
    assertEquals(0, p.getMaxPathLength());
    p.setMaxPathLength(-1);
    assertEquals(-1, p.getMaxPathLength());
    int[] maxPathLength = { -2, -10, Integer.MIN_VALUE };
    for (int i = 0; i < maxPathLength.length; i++) {
        try {
            p.setMaxPathLength(maxPathLength[i]);
            fail("InvalidParameterException expected ");
        } catch (InvalidParameterException e) {
        // expected
        }
    }
}
Also used : InvalidParameterException(java.security.InvalidParameterException) ByteArrayInputStream(java.io.ByteArrayInputStream) PKIXBuilderParameters(java.security.cert.PKIXBuilderParameters) X509CertSelector(java.security.cert.X509CertSelector) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Example 97 with X509CertSelector

use of java.security.cert.X509CertSelector in project robovm by robovm.

the class TestUtils method initCertPathSSCertChain.

public static void initCertPathSSCertChain() throws CertificateException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {
    // create certificates and CRLs
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bi = new ByteArrayInputStream(rootCert.getBytes());
    rootCertificateSS = (X509Certificate) cf.generateCertificate(bi);
    bi = new ByteArrayInputStream(endCert.getBytes());
    endCertificate = (X509Certificate) cf.generateCertificate(bi);
    BigInteger revokedSerialNumber = BigInteger.valueOf(1);
    crl = new MyCRL("X.509");
    //        X509CRL rootCRL = X509CRL;
    //        X509CRL interCRL = X509CRLExample.createCRL(interCert, interPair
    //                .getPrivate(), revokedSerialNumber);
    // create CertStore to support path building
    List<Object> list = new ArrayList<Object>();
    list.add(rootCertificateSS);
    list.add(endCertificate);
    CollectionCertStoreParameters params = new CollectionCertStoreParameters(list);
    store = CertStore.getInstance("Collection", params);
    theCertSelector = new X509CertSelector();
    theCertSelector.setCertificate(endCertificate);
    theCertSelector.setIssuer(endCertificate.getIssuerX500Principal().getEncoded());
    // build the path
    builder = CertPathBuilder.getInstance("PKIX");
}
Also used : CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) ByteArrayInputStream(java.io.ByteArrayInputStream) ArrayList(java.util.ArrayList) BigInteger(java.math.BigInteger) X509CertSelector(java.security.cert.X509CertSelector) CertificateFactory(java.security.cert.CertificateFactory)

Example 98 with X509CertSelector

use of java.security.cert.X509CertSelector in project XobotOS by xamarin.

the class CertPathValidatorUtilities method findTrustAnchor.

/**
     * Search the given Set of TrustAnchor's for one that is the
     * issuer of the given X509 certificate. Uses the specified
     * provider for signature verification, or the default provider
     * if null.
     *
     * @param cert the X509 certificate
     * @param trustAnchors a Set of TrustAnchor's
     * @param sigProvider the provider to use for signature verification
     *
     * @return the <code>TrustAnchor</code> object if found or
     * <code>null</code> if not.
     *
     * @exception AnnotatedException
     *                if a TrustAnchor was found but the signature verification
     *                on the given certificate has thrown an exception.
     */
protected static TrustAnchor findTrustAnchor(X509Certificate cert, Set trustAnchors, String sigProvider) throws AnnotatedException {
    TrustAnchor trust = null;
    PublicKey trustPublicKey = null;
    Exception invalidKeyEx = null;
    X509CertSelector certSelectX509 = new X509CertSelector();
    X500Principal certIssuer = getEncodedIssuerPrincipal(cert);
    try {
        certSelectX509.setSubject(certIssuer.getEncoded());
    } catch (IOException ex) {
        throw new AnnotatedException("Cannot set subject search criteria for trust anchor.", ex);
    }
    Iterator iter = trustAnchors.iterator();
    while (iter.hasNext() && trust == null) {
        trust = (TrustAnchor) iter.next();
        if (trust.getTrustedCert() != null) {
            if (certSelectX509.match(trust.getTrustedCert())) {
                trustPublicKey = trust.getTrustedCert().getPublicKey();
            } else {
                trust = null;
            }
        } else if (trust.getCAName() != null && trust.getCAPublicKey() != null) {
            try {
                X500Principal caName = new X500Principal(trust.getCAName());
                if (certIssuer.equals(caName)) {
                    trustPublicKey = trust.getCAPublicKey();
                } else {
                    trust = null;
                }
            } catch (IllegalArgumentException ex) {
                trust = null;
            }
        } else {
            trust = null;
        }
        if (trustPublicKey != null) {
            try {
                verifyX509Certificate(cert, trustPublicKey, sigProvider);
            } catch (Exception ex) {
                invalidKeyEx = ex;
                trust = null;
            }
        }
    }
    if (trust == null && invalidKeyEx != null) {
        throw new AnnotatedException("TrustAnchor found but certificate validation failed.", invalidKeyEx);
    }
    return trust;
}
Also used : PublicKey(java.security.PublicKey) DSAPublicKey(java.security.interfaces.DSAPublicKey) Iterator(java.util.Iterator) X500Principal(javax.security.auth.x500.X500Principal) TrustAnchor(java.security.cert.TrustAnchor) X509CertSelector(java.security.cert.X509CertSelector) IOException(java.io.IOException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ParseException(java.text.ParseException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertStoreException(java.security.cert.CertStoreException) CertificateParsingException(java.security.cert.CertificateParsingException) StoreException(org.bouncycastle.util.StoreException) IOException(java.io.IOException)

Example 99 with X509CertSelector

use of java.security.cert.X509CertSelector in project jdk8u_jdk by JetBrains.

the class ForwardBuilder method getMatchingCACerts.

/**
     * Retrieves all CA certificates which satisfy constraints
     * and requirements specified in the parameters and PKIX state.
     */
private void getMatchingCACerts(ForwardState currentState, List<CertStore> certStores, Collection<X509Certificate> caCerts) throws IOException {
    if (debug != null) {
        debug.println("ForwardBuilder.getMatchingCACerts()...");
    }
    int initialSize = caCerts.size();
    /*
         * Compose a CertSelector to filter out
         * certs which do not satisfy requirements.
         */
    X509CertSelector sel = null;
    if (currentState.isInitial()) {
        if (targetCertConstraints.getBasicConstraints() == -2) {
            // no need to continue: this means we never can match a CA cert
            return;
        }
        /* This means a CA is the target, so match on same stuff as
             * getMatchingEECerts
             */
        if (debug != null) {
            debug.println("ForwardBuilder.getMatchingCACerts(): " + "the target is a CA");
        }
        if (caTargetSelector == null) {
            caTargetSelector = (X509CertSelector) targetCertConstraints.clone();
            /*
                 * Policy processing optimizations
                 */
            if (buildParams.explicitPolicyRequired())
                caTargetSelector.setPolicy(getMatchingPolicies());
        }
        sel = caTargetSelector;
    } else {
        if (caSelector == null) {
            caSelector = new AdaptableX509CertSelector();
            /*
                 * Policy processing optimizations
                 */
            if (buildParams.explicitPolicyRequired())
                caSelector.setPolicy(getMatchingPolicies());
        }
        /*
             * Match on subject (issuer of previous cert)
             */
        caSelector.setSubject(currentState.issuerDN);
        /*
             * Match on subjectNamesTraversed (both DNs and AltNames)
             * (checks that current cert's name constraints permit it
             * to certify all the DNs and AltNames that have been traversed)
             */
        CertPathHelper.setPathToNames(caSelector, currentState.subjectNamesTraversed);
        /*
             * check the validity period
             */
        caSelector.setValidityPeriod(currentState.cert.getNotBefore(), currentState.cert.getNotAfter());
        sel = caSelector;
    }
    /*
         * For compatibility, conservatively, we don't check the path
         * length constraint of trusted anchors.  Please don't set the
         * basic constraints criterion unless the trusted certificate
         * matching is completed.
         */
    sel.setBasicConstraints(-1);
    for (X509Certificate trustedCert : trustedCerts) {
        if (sel.match(trustedCert)) {
            if (debug != null) {
                debug.println("ForwardBuilder.getMatchingCACerts: " + "found matching trust anchor." + "\n  SN: " + Debug.toHexString(trustedCert.getSerialNumber()) + "\n  Subject: " + trustedCert.getSubjectX500Principal() + "\n  Issuer: " + trustedCert.getIssuerX500Principal());
            }
            if (caCerts.add(trustedCert) && !searchAllCertStores) {
                return;
            }
        }
    }
    /*
         * The trusted certificate matching is completed. We need to match
         * on certificate validity date.
         */
    sel.setCertificateValid(buildParams.date());
    /*
         * Require CA certs with a pathLenConstraint that allows
         * at least as many CA certs that have already been traversed
         */
    sel.setBasicConstraints(currentState.traversedCACerts);
    /*
         * If we have already traversed as many CA certs as the maxPathLength
         * will allow us to, then we don't bother looking through these
         * certificate pairs. If maxPathLength has a value of -1, this
         * means it is unconstrained, so we always look through the
         * certificate pairs.
         */
    if (currentState.isInitial() || (buildParams.maxPathLength() == -1) || (buildParams.maxPathLength() > currentState.traversedCACerts)) {
        if (addMatchingCerts(sel, certStores, caCerts, searchAllCertStores) && !searchAllCertStores) {
            return;
        }
    }
    if (!currentState.isInitial() && Builder.USE_AIA) {
        // check for AuthorityInformationAccess extension
        AuthorityInfoAccessExtension aiaExt = currentState.cert.getAuthorityInfoAccessExtension();
        if (aiaExt != null) {
            getCerts(aiaExt, caCerts);
        }
    }
    if (debug != null) {
        int numCerts = caCerts.size() - initialSize;
        debug.println("ForwardBuilder.getMatchingCACerts: found " + numCerts + " CA certs");
    }
}
Also used : AuthorityInfoAccessExtension(sun.security.x509.AuthorityInfoAccessExtension) X509CertSelector(java.security.cert.X509CertSelector) X509Certificate(java.security.cert.X509Certificate)

Example 100 with X509CertSelector

use of java.security.cert.X509CertSelector in project jdk8u_jdk by JetBrains.

the class X509CertSelectorTest method testPrivateKeyValid.

/*
     * Tests matching on the private key validity component contained in the
     * certificate.
     */
private void testPrivateKeyValid() throws IOException, CertificateException {
    System.out.println("X.509 Certificate Match on privateKeyValid");
    // bad match
    X509CertSelector selector = new X509CertSelector();
    Calendar cal = Calendar.getInstance();
    cal.set(1968, 12, 31);
    selector.setPrivateKeyValid(cal.getTime());
    checkMatch(selector, cert, false);
    // good match
    DerInputStream in = new DerInputStream(cert.getExtensionValue("2.5.29.16"));
    byte[] encoded = in.getOctetString();
    PrivateKeyUsageExtension ext = new PrivateKeyUsageExtension(false, encoded);
    Date validDate = (Date) ext.get(PrivateKeyUsageExtension.NOT_BEFORE);
    selector.setPrivateKeyValid(validDate);
    checkMatch(selector, cert, true);
}
Also used : Calendar(java.util.Calendar) X509CertSelector(java.security.cert.X509CertSelector) DerInputStream(sun.security.util.DerInputStream) PrivateKeyUsageExtension(sun.security.x509.PrivateKeyUsageExtension) Date(java.util.Date)

Aggregations

X509CertSelector (java.security.cert.X509CertSelector)111 PKIXBuilderParameters (java.security.cert.PKIXBuilderParameters)24 X509Certificate (java.security.cert.X509Certificate)22 IOException (java.io.IOException)17 X500Principal (javax.security.auth.x500.X500Principal)16 CollectionCertStoreParameters (java.security.cert.CollectionCertStoreParameters)14 ArrayList (java.util.ArrayList)14 TrustAnchor (java.security.cert.TrustAnchor)12 CertificateFactory (java.security.cert.CertificateFactory)11 HashSet (java.util.HashSet)11 ByteArrayInputStream (java.io.ByteArrayInputStream)10 ASN1OctetString (org.apache.harmony.security.asn1.ASN1OctetString)10 PublicKey (java.security.PublicKey)9 CertPathBuilder (java.security.cert.CertPathBuilder)9 CertStore (java.security.cert.CertStore)9 KeyStore (java.security.KeyStore)8 BigInteger (java.math.BigInteger)7 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)7 Date (java.util.Date)7 CertificateException (java.security.cert.CertificateException)6