Search in sources :

Example 46 with CertPath

use of java.security.cert.CertPath in project oxTrust by GluuFederation.

the class SSLService method loadCertificatesAsPkiPathEncoded.

private static X509Certificate[] loadCertificatesAsPkiPathEncoded(InputStream is) throws Exception {
    try {
        CertificateFactory cf = getCertificateFactoryInstance();
        CertPath certPath = cf.generateCertPath(is, PKI_PATH_ENCODING);
        List<? extends Certificate> certs = certPath.getCertificates();
        ArrayList<X509Certificate> loadedCerts = new ArrayList<X509Certificate>();
        for (Iterator<? extends Certificate> itr = certs.iterator(); itr.hasNext(); ) {
            X509Certificate cert = (X509Certificate) itr.next();
            if (cert != null) {
                loadedCerts.add(cert);
            }
        }
        return loadedCerts.toArray(new X509Certificate[loadedCerts.size()]);
    } finally {
        IOUtils.closeQuietly(is);
    }
}
Also used : ArrayList(java.util.ArrayList) CertPath(java.security.cert.CertPath) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Example 47 with CertPath

use of java.security.cert.CertPath in project hono by eclipse.

the class DeviceRegistryBasedCertificateVerifier method verifyCertificate.

@Override
public CertificateVerificationResult verifyCertificate(final ConnectionId cid, final ServerNames serverName, final Boolean clientUsage, final boolean truncateCertificatePath, final CertificateMessage message, final DTLSSession session) {
    try {
        final CertPath certChain = message.getCertificateChain();
        if (certChain == null) {
            final AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.BAD_CERTIFICATE, session.getPeer());
            throw new HandshakeException("RPK not supported", alert);
        }
        final var certificates = certChain.getCertificates();
        if (certificates.isEmpty()) {
            final AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.BAD_CERTIFICATE, session.getPeer());
            throw new HandshakeException("client certificate chain must not be empty", alert);
        }
        if (clientUsage != null) {
            final Certificate clientCertificate = certificates.get(0);
            if (clientCertificate instanceof X509Certificate && !CertPathUtil.canBeUsedForAuthentication((X509Certificate) clientCertificate, clientUsage)) {
                final AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.BAD_CERTIFICATE, session.getPeer());
                throw new HandshakeException("certificate cannot be used for client authentication", alert);
            }
        }
        adapter.runOnContext((v) -> validateCertificateAndLoadDevice(cid, certChain, session));
        return null;
    } catch (HandshakeException e) {
        LOG.debug("certificate validation failed", e);
        return new CertificateVerificationResult(cid, e, null);
    }
}
Also used : CertPath(java.security.cert.CertPath) HandshakeException(org.eclipse.californium.scandium.dtls.HandshakeException) AlertMessage(org.eclipse.californium.scandium.dtls.AlertMessage) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) CertificateVerificationResult(org.eclipse.californium.scandium.dtls.CertificateVerificationResult)

Example 48 with CertPath

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

the class TrustedAuthorityValidator method isCertificateChainValid.

/**
 * Checks if a certificate chain is signed by a trusted authority.
 *
 * @param certificates 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)
        pkixParams.setRevocationEnabled(enableRevocation);
        if (enableRevocation) {
            List<X509CRL> crls = certRepo.getCRLs();
            if (!crls.isEmpty()) {
                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 49 with CertPath

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

the class KeyManagementUtils method validateCertificateChain.

private static void validateCertificateChain(KeyStore ks, List<X509Certificate> inCerts, boolean enableRevocation) {
    // 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);
        pbParams.setRevocationEnabled(enableRevocation);
        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) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Base64Exception(org.apache.cxf.common.util.Base64Exception) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 50 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)

Aggregations

CertPath (java.security.cert.CertPath)86 X509Certificate (java.security.cert.X509Certificate)36 CertificateFactory (java.security.cert.CertificateFactory)29 Certificate (java.security.cert.Certificate)19 CertPathValidator (java.security.cert.CertPathValidator)18 CertPathValidatorException (java.security.cert.CertPathValidatorException)18 MyCertPath (org.apache.harmony.security.tests.support.cert.MyCertPath)17 CertificateException (java.security.cert.CertificateException)15 ArrayList (java.util.ArrayList)15 PKIXParameters (java.security.cert.PKIXParameters)14 MyFailingCertPath (org.apache.harmony.security.tests.support.cert.MyFailingCertPath)14 TrustAnchor (java.security.cert.TrustAnchor)12 HashSet (java.util.HashSet)12 ByteArrayInputStream (java.io.ByteArrayInputStream)11 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)11 CertPathBuilderResult (java.security.cert.CertPathBuilderResult)11 PKIXBuilderParameters (java.security.cert.PKIXBuilderParameters)10 PKIXCertPathValidatorResult (java.security.cert.PKIXCertPathValidatorResult)10 X509CertSelector (java.security.cert.X509CertSelector)10 CertPathBuilder (java.security.cert.CertPathBuilder)9