Search in sources :

Example 86 with TrustAnchor

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

the class TrustedCertificateIndex method findByIssuerAndSignature.

public TrustAnchor findByIssuerAndSignature(X509Certificate cert) {
    X500Principal issuer = cert.getIssuerX500Principal();
    synchronized (subjectToTrustAnchors) {
        List<TrustAnchor> anchors = subjectToTrustAnchors.get(issuer);
        if (anchors == null) {
            return null;
        }
        for (TrustAnchor anchor : anchors) {
            PublicKey publicKey;
            try {
                X509Certificate caCert = anchor.getTrustedCert();
                if (caCert != null) {
                    publicKey = caCert.getPublicKey();
                } else {
                    publicKey = anchor.getCAPublicKey();
                }
                cert.verify(publicKey);
                return anchor;
            } catch (Exception ignored) {
            }
        }
    }
    return null;
}
Also used : PublicKey(java.security.PublicKey) X500Principal(javax.security.auth.x500.X500Principal) TrustAnchor(java.security.cert.TrustAnchor) X509Certificate(java.security.cert.X509Certificate) CertPathValidatorException(java.security.cert.CertPathValidatorException)

Example 87 with TrustAnchor

use of java.security.cert.TrustAnchor in project cloudstack by apache.

the class CertServiceImpl method validateChain.

private void validateChain(final List<Certificate> chain, final Certificate cert) {
    final List<Certificate> certs = new ArrayList<Certificate>();
    final Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();
    // adding for self signed certs
    certs.add(cert);
    certs.addAll(chain);
    for (final Certificate c : certs) {
        if (!(c instanceof X509Certificate)) {
            throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate");
        }
        final X509Certificate xCert = (X509Certificate) c;
        anchors.add(new TrustAnchor(xCert, null));
    }
    final X509CertSelector target = new X509CertSelector();
    target.setCertificate((X509Certificate) cert);
    PKIXBuilderParameters params = null;
    try {
        params = new PKIXBuilderParameters(anchors, target);
        params.setRevocationEnabled(false);
        params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs)));
        final CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
        builder.build(params);
    } catch (final InvalidAlgorithmParameterException | CertPathBuilderException | NoSuchAlgorithmException e) {
        throw new IllegalStateException("Invalid certificate chain", e);
    } catch (final NoSuchProviderException e) {
        throw new CloudRuntimeException("No provider for certificate validation", e);
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PKIXBuilderParameters(java.security.cert.PKIXBuilderParameters) ArrayList(java.util.ArrayList) TrustAnchor(java.security.cert.TrustAnchor) X509CertSelector(java.security.cert.X509CertSelector) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509Certificate(java.security.cert.X509Certificate) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) CertPathBuilder(java.security.cert.CertPathBuilder) NoSuchProviderException(java.security.NoSuchProviderException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) HashSet(java.util.HashSet)

Example 88 with TrustAnchor

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

the class ForwardBuilder method isPathCompleted.

/**
     * Verifies whether the input certificate completes the path.
     * First checks the cert against each trust anchor that was specified,
     * in order, and returns true if the cert matches the trust anchor
     * specified as a certificate or has the same key and subject of an anchor
     * specified as a trusted {pubkey, caname} pair.
     * If no match has been found, does a second check of the cert against
     * anchors specified as a trusted {pubkey, caname} pair to see if the cert
     * was issued by that anchor.
     * Returns false if none of the trust anchors are valid for this cert.
     *
     * @param cert the certificate to test
     * @return a boolean value indicating whether the cert completes the path.
     */
@Override
boolean isPathCompleted(X509Certificate cert) {
    List<TrustAnchor> otherAnchors = new ArrayList<>();
    // first, check if cert is already trusted
    for (TrustAnchor anchor : trustAnchors) {
        if (anchor.getTrustedCert() != null) {
            if (cert.equals(anchor.getTrustedCert())) {
                this.trustAnchor = anchor;
                return true;
            } else {
                continue;
            }
        }
        X500Principal principal = anchor.getCA();
        PublicKey publicKey = anchor.getCAPublicKey();
        if (principal != null && publicKey != null && principal.equals(cert.getSubjectX500Principal())) {
            if (publicKey.equals(cert.getPublicKey())) {
                // the cert itself is a trust anchor
                this.trustAnchor = anchor;
                return true;
            }
        // else, it is a self-issued certificate of the anchor
        }
        otherAnchors.add(anchor);
    }
    // next, check if cert is issued by anchor specified by key/name
    for (TrustAnchor anchor : otherAnchors) {
        X500Principal principal = anchor.getCA();
        PublicKey publicKey = anchor.getCAPublicKey();
        // Check subject/issuer name chaining
        if (principal == null || !principal.equals(cert.getIssuerX500Principal())) {
            continue;
        }
        // skip anchor if it contains a DSA key with no DSA params
        if (PKIX.isDSAPublicKeyWithoutParams(publicKey)) {
            continue;
        }
        /*
             * Check signature
             */
        try {
            cert.verify(publicKey, buildParams.sigProvider());
        } catch (InvalidKeyException ike) {
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() invalid " + "DSA key found");
            }
            continue;
        } catch (GeneralSecurityException e) {
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() " + "unexpected exception");
                e.printStackTrace();
            }
            continue;
        }
        this.trustAnchor = anchor;
        return true;
    }
    return false;
}
Also used : PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) X500Principal(javax.security.auth.x500.X500Principal) TrustAnchor(java.security.cert.TrustAnchor) InvalidKeyException(java.security.InvalidKeyException)

Example 89 with TrustAnchor

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

the class SignatureFile method loadKeyStore.

void loadKeyStore(String keyStoreName, boolean prompt) {
    if (!nullStream && keyStoreName == null) {
        keyStoreName = System.getProperty("user.home") + File.separator + ".keystore";
    }
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
        validator = CertPathValidator.getInstance("PKIX");
        Set<TrustAnchor> tas = new HashSet<>();
        try {
            KeyStore caks = KeyStoreUtil.getCacertsKeyStore();
            if (caks != null) {
                Enumeration<String> aliases = caks.aliases();
                while (aliases.hasMoreElements()) {
                    String a = aliases.nextElement();
                    try {
                        tas.add(new TrustAnchor((X509Certificate) caks.getCertificate(a), null));
                    } catch (Exception e2) {
                    // ignore, when a SecretkeyEntry does not include a cert
                    }
                }
            }
        } catch (Exception e) {
        // Ignore, if cacerts cannot be loaded
        }
        if (providerName == null) {
            store = KeyStore.getInstance(storetype);
        } else {
            store = KeyStore.getInstance(storetype, providerName);
        }
        // and on NT call ??
        if (token && storepass == null && !protectedPath && !KeyStoreUtil.isWindowsKeyStore(storetype)) {
            storepass = getPass(rb.getString("Enter.Passphrase.for.keystore."));
        } else if (!token && storepass == null && prompt) {
            storepass = getPass(rb.getString("Enter.Passphrase.for.keystore."));
        }
        try {
            if (nullStream) {
                store.load(null, storepass);
            } else {
                keyStoreName = keyStoreName.replace(File.separatorChar, '/');
                URL url = null;
                try {
                    url = new URL(keyStoreName);
                } catch (java.net.MalformedURLException e) {
                    // try as file
                    url = new File(keyStoreName).toURI().toURL();
                }
                InputStream is = null;
                try {
                    is = url.openStream();
                    store.load(is, storepass);
                } finally {
                    if (is != null) {
                        is.close();
                    }
                }
            }
            Enumeration<String> aliases = store.aliases();
            while (aliases.hasMoreElements()) {
                String a = aliases.nextElement();
                try {
                    X509Certificate c = (X509Certificate) store.getCertificate(a);
                    // PrivateKeyEntry
                    if (store.isCertificateEntry(a) || c.getSubjectDN().equals(c.getIssuerDN())) {
                        tas.add(new TrustAnchor(c, null));
                    }
                } catch (Exception e2) {
                // ignore, when a SecretkeyEntry does not include a cert
                }
            }
        } finally {
            try {
                pkixParameters = new PKIXParameters(tas);
                pkixParameters.setRevocationEnabled(false);
            } catch (InvalidAlgorithmParameterException ex) {
            // Only if tas is empty
            }
        }
    } catch (IOException ioe) {
        throw new RuntimeException(rb.getString("keystore.load.") + ioe.getMessage());
    } catch (java.security.cert.CertificateException ce) {
        throw new RuntimeException(rb.getString("certificate.exception.") + ce.getMessage());
    } catch (NoSuchProviderException pe) {
        throw new RuntimeException(rb.getString("keystore.load.") + pe.getMessage());
    } catch (NoSuchAlgorithmException nsae) {
        throw new RuntimeException(rb.getString("keystore.load.") + nsae.getMessage());
    } catch (KeyStoreException kse) {
        throw new RuntimeException(rb.getString("unable.to.instantiate.keystore.class.") + kse.getMessage());
    }
}
Also used : TrustAnchor(java.security.cert.TrustAnchor) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate) URISyntaxException(java.net.URISyntaxException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) SocketTimeoutException(java.net.SocketTimeoutException) CertificateException(java.security.cert.CertificateException) URL(java.net.URL) PKIXParameters(java.security.cert.PKIXParameters)

Example 90 with TrustAnchor

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

the class SignatureFile method validateCertChain.

void validateCertChain(List<? extends Certificate> certs) throws Exception {
    int cpLen = 0;
    out: for (; cpLen < certs.size(); cpLen++) {
        for (TrustAnchor ta : pkixParameters.getTrustAnchors()) {
            if (ta.getTrustedCert().equals(certs.get(cpLen))) {
                break out;
            }
        }
    }
    if (cpLen > 0) {
        CertPath cp = certificateFactory.generateCertPath((cpLen == certs.size()) ? certs : certs.subList(0, cpLen));
        validator.validate(cp, pkixParameters);
    }
}
Also used : TrustAnchor(java.security.cert.TrustAnchor) CertPath(java.security.cert.CertPath)

Aggregations

TrustAnchor (java.security.cert.TrustAnchor)103 X509Certificate (java.security.cert.X509Certificate)47 PublicKey (java.security.PublicKey)26 HashSet (java.util.HashSet)25 X500Principal (javax.security.auth.x500.X500Principal)23 PKIXParameters (java.security.cert.PKIXParameters)20 PKIXBuilderParameters (java.security.cert.PKIXBuilderParameters)19 X509CertSelector (java.security.cert.X509CertSelector)18 TestKeyPair (org.apache.harmony.security.tests.support.TestKeyPair)16 CertificateFactory (java.security.cert.CertificateFactory)15 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)14 CertPathValidatorException (java.security.cert.CertPathValidatorException)14 PKIXCertPathValidatorResult (java.security.cert.PKIXCertPathValidatorResult)14 ArrayList (java.util.ArrayList)14 CollectionCertStoreParameters (java.security.cert.CollectionCertStoreParameters)13 PKIXCertPathBuilderResult (java.security.cert.PKIXCertPathBuilderResult)13 IOException (java.io.IOException)12 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)10 CertPathBuilder (java.security.cert.CertPathBuilder)10 CertificateException (java.security.cert.CertificateException)10