Example usage for java.security.cert TrustAnchor TrustAnchor

List of usage examples for java.security.cert TrustAnchor TrustAnchor

Introduction

In this page you can find the example usage for java.security.cert TrustAnchor TrustAnchor.

Prototype

public TrustAnchor(X509Certificate trustedCert, byte[] nameConstraints) 

Source Link

Document

Creates an instance of TrustAnchor with the specified X509Certificate and optional name constraints, which are intended to be used as additional constraints when validating an X.509 certification path.

Usage

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    List mylist = new ArrayList();
    FileInputStream in = new FileInputStream(args[0]);
    Certificate c = cf.generateCertificate(in);
    mylist.add(c);/*  w  ww  . j av  a 2  s  .com*/

    CertPath cp = cf.generateCertPath(mylist);

    Certificate trust = cf.generateCertificate(in);
    TrustAnchor anchor = new TrustAnchor((X509Certificate) trust, null);
    PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));
    params.setRevocationEnabled(false);
    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
    PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
    System.out.println(result);
}

From source file:Main.java

public static CertPathParameters getCertPathParameters() throws InvalidAlgorithmParameterException {
    if ((rootCertificateSS == null) || (theCertSelector == null) || (builder == null)) {
        throw new RuntimeException("Call initCertPathSSCertChain prior to buildCertPath");
    }/*from  w w w  .j av a2s.com*/
    PKIXBuilderParameters buildParams = new PKIXBuilderParameters(
            Collections.singleton(new TrustAnchor(rootCertificateSS, null)), theCertSelector);

    buildParams.addCertStore(store);
    buildParams.setRevocationEnabled(false);

    return buildParams;

}

From source file:org.globus.security.stores.ResourceTrustAnchor.java

@Override
protected TrustAnchor create(Resource resource) throws ResourceStoreException {
    X509Certificate certificate;//ww w  .jav  a  2 s . c  o m
    try {
        certificate = CertificateLoadUtil.loadCertificate(resource.getInputStream());
    } catch (IOException e) {
        throw new ResourceStoreException(e);
    } catch (GeneralSecurityException e) {
        throw new ResourceStoreException(e);
    }

    return new TrustAnchor(certificate, null);
}

From source file:Main.java

/**
 * Creates <code>TrustAnchor</code> instance
 * constructed using self signed test certificate
 *
 * @return <code>TrustAnchor</code> instance
 *///from w ww .j  a  va 2 s. co  m
public static TrustAnchor getTrustAnchor() {
    CertificateFactory cf = null;
    try {
        cf = CertificateFactory.getInstance(certType);
    } catch (CertificateException e) {
        // requested cert type is not available in the
        // default provider package or any of the other provider packages
        // that were searched
        throw new RuntimeException(e);
    }
    BufferedInputStream bis = null;
    try {
        bis = new BufferedInputStream(new ByteArrayInputStream(getEncodedX509Certificate()));
        X509Certificate c1 = (X509Certificate) cf.generateCertificate(bis);

        return new TrustAnchor(c1, null);
    } catch (Exception e) {
        // all failures are fatal
        throw new RuntimeException(e);
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ign) {
            }
        }
    }
}

From source file:Main.java

public static PKIXCertPathValidatorResult validateCertificate(X509Certificate entity,
        X509Certificate intermediate, X509Certificate CA) throws Exception {
    /*  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
      ks.load(null, null);//ww  w .  ja va2s. co  m
      String alias = "validationCA";
      ks.setCertificateEntry(alias, CA);
            
     */
    /*  KeyStore intermediatesStore = KeyStore.getInstance(KeyStore.getDefaultType());
    intermediatesStore.load(null, null);
    String alias_intermediate = "validationIntermediate";
    intermediatesStore.setCertificateEntry(alias_intermediate, intermediate);*//*
                                                                                        
                                                                                        
                                                                                X509CertSelector target = new X509CertSelector();
                                                                                target.setCertificate(entity);
                                                                                PKIXBuilderParameters params = new PKIXBuilderParameters(ks, target);
                                                                                ArrayList<X509Certificate> chain = new ArrayList<>();
                                                                                chain.add(intermediate);
                                                                                chain.add(intermediate);
                                                                                CertStoreParameters intermediates = new CollectionCertStoreParameters(chain);
                                                                                params.addCertStore(CertStore.getInstance("Collection", intermediates));
                                                                                CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
                                                                                 *//*
                                                                                    * If build() returns successfully, the certificate is valid. More details
                                                                                    * about the valid path can be obtained through the PKIXBuilderResult.
                                                                                    * If no valid path can be found, a CertPathBuilderException is thrown.
                                                                                    *//*
                                                                                          PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult)builder.build(params);
                                                                                          return result;*/

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    CertPath certPath = certificateFactory
            .generateCertPath(Arrays.asList(new X509Certificate[] { entity, intermediate }));

    TrustAnchor trustAnchor = new TrustAnchor(CA, null);

    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");

    PKIXParameters pkixParams = new PKIXParameters(Collections.singleton(trustAnchor));
    pkixParams.setRevocationEnabled(true);

    return (PKIXCertPathValidatorResult) cpv.validate(certPath, pkixParams);
}

From source file:be.apsu.extremon.probes.ocsp.OCSPProbe.java

public OCSPProbe() {
    CertificateFactory certificateFactory = null;

    try {//w ww .j a va 2 s.  c om
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException cex) {
        log("Don't Have Crypto Libs:" + cex.getMessage());
        System.exit(1);
    }

    try {
        certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(confStr("certificate"))));
        trustAnchorCert = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(confStr("trustanchor"))));
    } catch (CertificateException cex) {
        log("certificate and trustanchor required in config:" + cex.getMessage());
        System.exit(2);
    }

    this.delay = confInt("delay", DEFAULT_DELAY);

    try {
        List<X509Certificate> certs = new ArrayList<X509Certificate>();
        certs.add(this.certificate);
        this.certificatePath = (CertPath) certificateFactory.generateCertPath(certs);

        TrustAnchor trustAnchor = new TrustAnchor(this.trustAnchorCert, null);
        Set<TrustAnchor> trustedCertsSet = new HashSet<TrustAnchor>();
        trustedCertsSet.add(trustAnchor);

        Set<X509Certificate> certSet = new HashSet<X509Certificate>();
        certSet.add(this.trustAnchorCert);
        CertStoreParameters storeParams = new CollectionCertStoreParameters(certSet);
        CertStore store = CertStore.getInstance("Collection", storeParams);

        pkixParams = new PKIXParameters(trustedCertsSet);
        pkixParams.addCertStore(store);

        Security.setProperty("ocsp.enable", "true");
        Security.setProperty("ocsp.responderURL", confStr("url"));
        Security.setProperty("ocsp.responderCertSubjectName",
                this.trustAnchorCert.getSubjectX500Principal().getName());

        this.certificatePathValidator = CertPathValidator.getInstance("PKIX");
    } catch (InvalidAlgorithmParameterException iaex) {
        log("Invalid Algorithm Parameter:" + iaex.getMessage());
        System.exit(3);
    } catch (CertificateException cex) {
        log("Certificate Exception:" + cex.getMessage());
        System.exit(4);
    } catch (NoSuchAlgorithmException nsaex) {
        log("No Such Algorithm:" + nsaex.getMessage());
        System.exit(5);
    } catch (Exception ex) {
        log(ex.getMessage());
        System.exit(6);
    }

    start();
    log("Initialized");
}

From source file:com.sk89q.mclauncher.security.X509KeyStore.java

/**
 * Verify that a given certificate is trusted.
 * /*from  w w  w. j  ava 2  s.c o  m*/
 * @param chain certificate chain
 * @throws CertPathBuilderException thrown on verification error
 * @throws CertificateVerificationException thrown on any error
 */
public void verify(X509Certificate[] chain) throws CertificateVerificationException, CertPathBuilderException {
    try {
        X509CertSelector selector = new X509CertSelector();
        selector.setCertificate(chain[0]);

        // Root certificates
        Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
        for (X509Certificate rootCert : rootCerts) {
            trustAnchors.add(new TrustAnchor(rootCert, null));
        }

        PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector);

        pkixParams.setRevocationEnabled(true);

        // Built-in intermediate certificates
        pkixParams.addCertStore(
                CertStore.getInstance("Collection", new CollectionCertStoreParameters(intermediateCerts)));

        // Additional intermediate certificates
        pkixParams.addCertStore(
                CertStore.getInstance("Collection", new CollectionCertStoreParameters(Arrays.asList(chain))));

        CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
        builder.build(pkixParams); // Will error on failure to verify
    } catch (InvalidAlgorithmParameterException e) {
        throw new CertificateVerificationException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateVerificationException(e);
    }
}

From source file:com.vmware.identity.idm.IDPConfig.java

/**
 * Validate the chain is in the required order user's certificate first,
 * root CA certificate last including the case of only root CA is present.
 * Also validate that there is only one chain, which consists of all the
 * certificates listed./*from   w  ww.  j a v  a2 s . com*/
 */
private static boolean validateSingleX509CertChain(List<X509Certificate> chain)
        throws ExternalIDPExtraneousCertsInCertChainException, ExternalIDPCertChainInvalidTrustedPathException {
    final String ALGO_PKIX = "PKIX"; //for X.509

    final String CERTSTORE_PROVIDER_COLLECTION = "Collection";

    try {
        Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();
        anchors.add(new TrustAnchor(chain.get(chain.size() - 1), null));

        X509CertSelector targetCertSelector = new X509CertSelector();
        targetCertSelector.setCertificate(chain.get(0));

        CertStore builderStore = CertStore.getInstance(CERTSTORE_PROVIDER_COLLECTION,
                new CollectionCertStoreParameters(chain));

        PKIXBuilderParameters buildParams = new PKIXBuilderParameters(anchors, targetCertSelector);
        buildParams.addCertStore(builderStore);
        buildParams.setRevocationEnabled(false);

        CertPathBuilder pathBuilder = CertPathBuilder.getInstance(ALGO_PKIX);
        CertPathBuilderResult builderResult = pathBuilder.build(buildParams);

        if (chain.size() - 1 != builderResult.getCertPath().getCertificates().size()) {
            throw new ExternalIDPExtraneousCertsInCertChainException(chain);
        }
        return true;

    } catch (CertPathBuilderException cpbe) {
        throw new ExternalIDPCertChainInvalidTrustedPathException(cpbe.getMessage(), chain); // no need to chain the exception.
    } catch (GeneralSecurityException gse) {
        throw new ExternalIDPCertChainInvalidTrustedPathException(gse.getMessage(), chain);
    }
}

From source file:mx.com.quadrum.service.util.firma.ValidacionesCertificado.java

/**
 * Mtodo que valida si el certificado es apocrifo, no valido ante el SAT
 *
 * @param cert Certificado a validar/*from  w  w w  . j a v a  2s.co  m*/
 * @return true si el certificado es apocrifo, en otro caso false
 */
public boolean validateCertificate() {
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        List mylist = new ArrayList();
        TrustAnchor anchor = new TrustAnchor(
                (java.security.cert.X509Certificate) importCertificate(cerInputStream), null);
        mylist.add(certificado);
        CertPath cp = cf.generateCertPath(mylist);
        PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));
        params.setRevocationEnabled(false);
        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
        return true;
    } catch (Exception ex) {
        System.out.println("Expecion causada a proposito :P");
    }
    return false;
}

From source file:com.blackducksoftware.integration.hub.jenkins.site.BlackDuckHubUpdateSite.java

/**
 * Verifies the signature in the update center data file.
 *//*from   www  .jav  a2  s . c  o  m*/
private FormValidation verifySignature(final JSONObject o) throws IOException {
    try {
        FormValidation warning = null;

        final JSONObject signature = o.getJSONObject("signature");
        if (signature.isNullObject()) {
            return FormValidation.error("No signature block found in update center '" + getId() + "'");
        }
        o.remove("signature");

        final List<X509Certificate> certs = new ArrayList<X509Certificate>();
        {// load and verify certificates
            final CertificateFactory cf = CertificateFactory.getInstance("X509");
            for (final Object cert : signature.getJSONArray("certificates")) {
                final X509Certificate c = (X509Certificate) cf.generateCertificate(
                        new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray())));
                try {
                    c.checkValidity();
                } catch (final CertificateExpiredException e) { // even if the certificate isn't valid yet,
                    // we'll proceed it anyway
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s has expired in update center '%s'", cert.toString(), getId()));
                } catch (final CertificateNotYetValidException e) {
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s is not yet valid in update center '%s'", cert.toString(), getId()));
                }
                certs.add(c);
            }

            // all default root CAs in JVM are trusted, plus certs bundled in Jenkins
            final Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); // CertificateUtil.getDefaultRootCAs();
            final ServletContext context = Jenkins.getInstance().servletContext;
            anchors.add(new TrustAnchor(loadLicenseCaCertificate(), null));
            for (final String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) {
                if (cert.endsWith(".txt")) {
                    continue; // skip text files that are meant to be documentation
                }
                final InputStream stream = context.getResourceAsStream(cert);
                if (stream != null) {
                    try {
                        anchors.add(new TrustAnchor((X509Certificate) cf.generateCertificate(stream), null));
                    } finally {
                        IOUtils.closeQuietly(stream);
                    }
                }
            }
            CertificateUtil.validatePath(certs, anchors);
        }

        // this is for computing a digest to check sanity
        final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        final DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1);

        // this is for computing a signature
        final Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(certs.get(0));
        final SignatureOutputStream sos = new SignatureOutputStream(sig);

        // until JENKINS-11110 fix, UC used to serve invalid digest (and therefore unverifiable signature)
        // that only covers the earlier portion of the file. This was caused by the lack of close() call
        // in the canonical writing, which apparently leave some bytes somewhere that's not flushed to
        // the digest output stream. This affects Jenkins [1.424,1,431].
        // Jenkins 1.432 shipped with the "fix" (1eb0c64abb3794edce29cbb1de50c93fa03a8229) that made it
        // compute the correct digest, but it breaks all the existing UC json metadata out there. We then
        // quickly discovered ourselves in the catch-22 situation. If we generate UC with the correct signature,
        // it'll cut off [1.424,1.431] from the UC. But if we don't, we'll cut off [1.432,*).
        //
        // In 1.433, we revisited 1eb0c64abb3794edce29cbb1de50c93fa03a8229 so that the original "digest"/"signature"
        // pair continues to be generated in a buggy form, while "correct_digest"/"correct_signature" are generated
        // correctly.
        //
        // Jenkins should ignore "digest"/"signature" pair. Accepting it creates a vulnerability that allows
        // the attacker to inject a fragment at the end of the json.
        o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos, sos), "UTF-8")).close();

        // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n
        // (which is more likely than someone tampering with update center), we can tell
        final String computedDigest = new String(Base64.encode(sha1.digest()));
        final String providedDigest = signature.optString("correct_digest");
        if (providedDigest == null) {
            return FormValidation.error("No correct_digest parameter in update center '" + getId()
                    + "'. This metadata appears to be old.");
        }
        if (!computedDigest.equalsIgnoreCase(providedDigest)) {
            return FormValidation.error("Digest mismatch: " + computedDigest + " vs " + providedDigest
                    + " in update center '" + getId() + "'");
        }

        final String providedSignature = signature.getString("correct_signature");
        if (!sig.verify(Base64.decode(providedSignature.toCharArray()))) {
            return FormValidation.error(
                    "Signature in the update center doesn't match with the certificate in update center '"
                            + getId() + "'");
        }

        if (warning != null) {
            return warning;
        }
        return FormValidation.ok();
    } catch (final GeneralSecurityException e) {
        return FormValidation.error(e, "Signature verification failed in the update center '" + getId() + "'");
    }
}