Search in sources :

Example 31 with CertPath

use of java.security.cert.CertPath in project cxf by apache.

the class KeyManagementUtils method validateCertificateChain.

public static void validateCertificateChain(KeyStore ks, List<X509Certificate> inCerts) {
    // Initial chain validation, to be enhanced as needed
    try {
        X509CertSelector certSelect = new X509CertSelector();
        certSelect.setCertificate(inCerts.get(0));
        PKIXBuilderParameters pbParams = new PKIXBuilderParameters(ks, certSelect);
        pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(inCerts)));
        pbParams.setMaxPathLength(-1);
        pbParams.setRevocationEnabled(false);
        CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams);
        CertPath certPath = buildResult.getCertPath();
        CertPathValidator.getInstance("PKIX").validate(certPath, pbParams);
    } catch (Exception ex) {
        LOG.warning("Certificate path validation error");
        throw new JoseException(ex);
    }
}
Also used : CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) PKIXBuilderParameters(java.security.cert.PKIXBuilderParameters) CertPathBuilderResult(java.security.cert.CertPathBuilderResult) X509CertSelector(java.security.cert.X509CertSelector) CertPath(java.security.cert.CertPath) KeyStoreException(java.security.KeyStoreException) JwkException(org.apache.cxf.rs.security.jose.jwk.JwkException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Base64Exception(org.apache.cxf.common.util.Base64Exception) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 32 with CertPath

use of java.security.cert.CertPath in project cxf by apache.

the class TrustedAuthorityValidator method isCertificateChainValid.

/**
 * Checks if a certificate is signed by a trusted authority.
 *
 * @param x509Certificate to check
 * @return the validity state of the certificate
 */
boolean isCertificateChainValid(List<X509Certificate> certificates) {
    X509Certificate targetCert = certificates.get(0);
    X509CertSelector selector = new X509CertSelector();
    selector.setCertificate(targetCert);
    try {
        List<X509Certificate> intermediateCerts = certRepo.getCaCerts();
        List<X509Certificate> trustedAuthorityCerts = certRepo.getTrustedCaCerts();
        Set<TrustAnchor> trustAnchors = asTrustAnchors(trustedAuthorityCerts);
        CertStoreParameters intermediateParams = new CollectionCertStoreParameters(intermediateCerts);
        CertStoreParameters certificateParams = new CollectionCertStoreParameters(certificates);
        PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector);
        pkixParams.addCertStore(CertStore.getInstance("Collection", intermediateParams));
        pkixParams.addCertStore(CertStore.getInstance("Collection", certificateParams));
        pkixParams.setRevocationEnabled(false);
        CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
        CertPath certPath = builder.build(pkixParams).getCertPath();
        // Now validate the CertPath (including CRL checking)
        if (enableRevocation) {
            List<X509CRL> crls = certRepo.getCRLs();
            if (!crls.isEmpty()) {
                pkixParams.setRevocationEnabled(true);
                CertStoreParameters crlParams = new CollectionCertStoreParameters(crls);
                pkixParams.addCertStore(CertStore.getInstance("Collection", crlParams));
            }
        }
        CertPathValidator validator = CertPathValidator.getInstance("PKIX");
        validator.validate(certPath, pkixParams);
    } catch (InvalidAlgorithmParameterException e) {
        LOG.log(Level.WARNING, "Invalid algorithm parameter by certificate chain validation. " + "It is likely that issuer certificates are not found in XKMS trusted storage. " + e.getMessage(), e);
        return false;
    } catch (NoSuchAlgorithmException e) {
        LOG.log(Level.WARNING, "Unknown algorithm by trust chain validation: " + e.getMessage(), e);
        return false;
    } catch (CertPathBuilderException e) {
        LOG.log(Level.WARNING, "Cannot build certification path: " + e.getMessage(), e);
        return false;
    } catch (CertPathValidatorException e) {
        LOG.log(Level.WARNING, "Cannot vaidate certification path: " + e.getMessage(), e);
        return false;
    }
    return true;
}
Also used : X509CRL(java.security.cert.X509CRL) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PKIXBuilderParameters(java.security.cert.PKIXBuilderParameters) X509CertSelector(java.security.cert.X509CertSelector) TrustAnchor(java.security.cert.TrustAnchor) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509Certificate(java.security.cert.X509Certificate) CertStoreParameters(java.security.cert.CertStoreParameters) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) CertPathValidator(java.security.cert.CertPathValidator) CertPathValidatorException(java.security.cert.CertPathValidatorException) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) CertPathBuilder(java.security.cert.CertPathBuilder) CertPath(java.security.cert.CertPath)

Example 33 with CertPath

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

the class CertificateFactoryTest method testCertPathEncoding.

private void testCertPathEncoding(CertificateFactory cf, List<X509Certificate> expectedCerts, String encoding) throws Exception {
    final String providerName = cf.getProvider().getName() + "[" + encoding + "]";
    final CertPath pathFromList = cf.generateCertPath(expectedCerts);
    // Create a copy we can modify and discard.
    final byte[] encodedCopy;
    if (encoding == null) {
        encodedCopy = pathFromList.getEncoded();
        assertNotNull(providerName, encodedCopy);
        // check idempotence
        assertEquals(providerName, Arrays.toString(pathFromList.getEncoded()), Arrays.toString(encodedCopy));
    } else {
        encodedCopy = pathFromList.getEncoded(encoding);
        assertNotNull(providerName, encodedCopy);
        // check idempotence
        assertEquals(providerName, Arrays.toString(pathFromList.getEncoded(encoding)), Arrays.toString(encodedCopy));
    }
    // Try to modify byte array.
    encodedCopy[0] ^= (byte) 0xFF;
    // Get a real copy we will use if the test proceeds.
    final byte[] encoded;
    if (encoding == null) {
        encoded = pathFromList.getEncoded();
        assertNotNull(providerName, encodedCopy);
        // check idempotence
        assertEquals(providerName, Arrays.toString(pathFromList.getEncoded()), Arrays.toString(encoded));
    } else {
        encoded = pathFromList.getEncoded(encoding);
        assertNotNull(providerName, encodedCopy);
        // check idempotence
        assertEquals(providerName, Arrays.toString(pathFromList.getEncoded(encoding)), Arrays.toString(encoded));
    }
    assertFalse(providerName, Arrays.toString(encoded).equals(Arrays.toString(encodedCopy)));
    encodedCopy[0] ^= (byte) 0xFF;
    assertEquals(providerName, Arrays.toString(encoded), Arrays.toString(encodedCopy));
    final CertPath actualPath;
    if (encoding == null) {
        actualPath = cf.generateCertPath(new ByteArrayInputStream(encoded));
    } else {
        actualPath = cf.generateCertPath(new ByteArrayInputStream(encoded), encoding);
    }
    // PKCS7 certificate bags are not guaranteed to be in order.
    final List<? extends Certificate> actualCerts;
    if (!"PKCS7".equals(encoding)) {
        actualCerts = actualPath.getCertificates();
        assertEquals(providerName, expectedCerts, actualCerts);
    } else {
        actualCerts = pathFromList.getCertificates();
    }
    try {
        actualCerts.remove(0);
        fail("List of certificate should be immutable");
    } catch (UnsupportedOperationException expected) {
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(actualPath);
    oos.close();
    byte[] serialized = baos.toByteArray();
    ByteArrayInputStream bais = new ByteArrayInputStream(serialized);
    ObjectInputStream ois = new ObjectInputStream(bais);
    Object output = ois.readObject();
    assertTrue(providerName, output instanceof CertPath);
    assertEquals(providerName, actualPath, (CertPath) output);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CertPath(java.security.cert.CertPath) ObjectOutputStream(java.io.ObjectOutputStream) ObjectInputStream(java.io.ObjectInputStream)

Example 34 with CertPath

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

the class CertificateFactoryTest method testGenerateCertPath.

/* CertPath tests */
public void testGenerateCertPath() throws Exception {
    KeyHolder ca = generateCertificate(true, null);
    KeyHolder cert1 = generateCertificate(true, ca);
    KeyHolder cert2 = generateCertificate(false, cert1);
    KeyHolder cert3 = generateCertificate(false, cert2);
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(cert3.certificate);
    certs.add(cert2.certificate);
    certs.add(cert1.certificate);
    List<X509Certificate> duplicatedCerts = new ArrayList<X509Certificate>(certs);
    duplicatedCerts.add(cert2.certificate);
    Provider[] providers = Security.getProviders("CertificateFactory.X509");
    for (Provider p : providers) {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509", p);
        // Duplicate certificates can cause an exception.
        {
            final CertPath duplicatedPath = cf.generateCertPath(duplicatedCerts);
            try {
                duplicatedPath.getEncoded();
                if (StandardNames.IS_RI) {
                    fail("duplicate certificates should cause failure: " + p.getName());
                }
            } catch (CertificateEncodingException expected) {
                if (!StandardNames.IS_RI) {
                    fail("duplicate certificates should pass: " + p.getName());
                }
            }
        }
        testCertPathEncoding(cf, certs, null);
        /* Make sure all encoding entries are the same. */
        final Iterator<String> it1 = cf.getCertPathEncodings();
        final Iterator<String> it2 = cf.generateCertPath(certs).getEncodings();
        for (; ; ) {
            assertEquals(p.getName(), it1.hasNext(), it2.hasNext());
            if (!it1.hasNext()) {
                break;
            }
            String encoding = it1.next();
            assertEquals(p.getName(), encoding, it2.next());
            try {
                it1.remove();
                fail("Should not be able to remove from iterator");
            } catch (UnsupportedOperationException expected) {
            }
            try {
                it2.remove();
                fail("Should not be able to remove from iterator");
            } catch (UnsupportedOperationException expected) {
            }
            /* Now test using this encoding. */
            testCertPathEncoding(cf, certs, encoding);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) CertificateEncodingException(java.security.cert.CertificateEncodingException) CertPath(java.security.cert.CertPath) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) Provider(java.security.Provider)

Example 35 with CertPath

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

the class CodeSignerTest method testEqualsObject.

/**
     * Test various assertions about equals()
     */
public final void testEqualsObject() {
    CodeSigner one = new CodeSigner(cpath, ts);
    CodeSigner two = new CodeSigner(cpath, ts);
    CodeSigner three = new CodeSigner(cpath, null);
    CertPath cpath2 = TestCertUtils.genCertPath(5, 3);
    CodeSigner four = new CodeSigner(cpath2, null);
    assertTrue(one.equals(one));
    assertTrue(one.equals(two));
    assertTrue(two.equals(one));
    assertFalse(one.equals(three));
    assertFalse(three.equals(one));
    assertTrue(three.equals(three));
    // different CertPaths
    assertFalse(three.equals(four));
    // special cases
    assertFalse(one.equals(null));
    assertFalse(one.equals(new Object()));
}
Also used : CertPath(java.security.cert.CertPath) CodeSigner(java.security.CodeSigner)

Aggregations

CertPath (java.security.cert.CertPath)55 X509Certificate (java.security.cert.X509Certificate)17 MyCertPath (org.apache.harmony.security.tests.support.cert.MyCertPath)16 CertificateFactory (java.security.cert.CertificateFactory)15 MyFailingCertPath (org.apache.harmony.security.tests.support.cert.MyFailingCertPath)14 CertPathValidatorException (java.security.cert.CertPathValidatorException)13 ArrayList (java.util.ArrayList)10 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)9 CertPathValidator (java.security.cert.CertPathValidator)9 CertPathBuilderResult (java.security.cert.CertPathBuilderResult)8 TrustAnchor (java.security.cert.TrustAnchor)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 Certificate (java.security.cert.Certificate)7 PKIXCertPathValidatorResult (java.security.cert.PKIXCertPathValidatorResult)7 PKIXParameters (java.security.cert.PKIXParameters)7 HashSet (java.util.HashSet)7 CertPathBuilder (java.security.cert.CertPathBuilder)6 CertPathBuilderException (java.security.cert.CertPathBuilderException)6 CertificateException (java.security.cert.CertificateException)6 PKIXBuilderParameters (java.security.cert.PKIXBuilderParameters)6