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:org.ejbca.util.CertTools.java

/**
 * Method to create certificate path and to check it's validity from a list of certificates.
 * The list of certificates should only contain one root certificate.
 *
 * @param certlist//  w  w w  .jav  a 2  s .c o  m
 * @return the certificatepath with the root CA at the end, either collection of Certificate or byte[] (der encoded certs)
 * @throws CertPathValidatorException if the certificate chain can not be constructed
 * @throws InvalidAlgorithmParameterException 
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 * @throws CertificateException 
 */
public static Collection<Certificate> createCertChain(Collection<?> certlistin)
        throws CertPathValidatorException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
        NoSuchProviderException, CertificateException {
    ArrayList<Certificate> returnval = new ArrayList<Certificate>();

    Collection<Certificate> certlist = orderCertificateChain(certlistin);

    // set certificate chain
    Certificate rootcert = null;
    ArrayList<Certificate> calist = new ArrayList<Certificate>();
    Iterator<Certificate> iter = certlist.iterator();
    while (iter.hasNext()) {
        Certificate next = iter.next();
        if (CertTools.isSelfSigned(next)) {
            rootcert = next;
        } else {
            calist.add(next);
        }
    }

    if (calist.isEmpty()) {
        // only one root cert, no certchain
        returnval.add(rootcert);
    } else {
        // We need a bit special handling for CV certificates because those can not be handled using a PKIX CertPathValidator
        Certificate test = calist.get(0);
        if (test.getType().equals("CVC")) {
            if (calist.size() == 1) {
                returnval.add(test);
                returnval.add(rootcert);
            } else {
                throw new CertPathValidatorException(
                        "CVC certificate chain can not be of length longer than two.");
            }
        } else {
            // Normal X509 certificates
            HashSet<TrustAnchor> trustancors = new HashSet<TrustAnchor>();
            TrustAnchor trustanchor = null;
            trustanchor = new TrustAnchor((X509Certificate) rootcert, null);
            trustancors.add(trustanchor);

            // Create the parameters for the validator
            PKIXParameters params = new PKIXParameters(trustancors);

            // Disable CRL checking since we are not supplying any CRLs
            params.setRevocationEnabled(false);
            params.setDate(new Date());

            // Create the validator and validate the path
            CertPathValidator certPathValidator = CertPathValidator
                    .getInstance(CertPathValidator.getDefaultType(), "BC");
            CertificateFactory fact = CertTools.getCertificateFactory();
            CertPath certpath = fact.generateCertPath(calist);

            CertPathValidatorResult result = certPathValidator.validate(certpath, params);

            // Get the certificates validate in the path
            PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
            returnval.addAll(certpath.getCertificates());

            // Get the CA used to validate this path
            TrustAnchor ta = pkixResult.getTrustAnchor();
            X509Certificate cert = ta.getTrustedCert();
            returnval.add(cert);
        }
    }
    return returnval;
}

From source file:org.globus.gsi.stores.PEMKeyStore.java

/**
 * Add a certificate to the keystore./*  ww  w . j  a  va  2 s  .c  o m*/
 *
 * @param alias
 *            The certificate alias.
 * @param certificate
 *            The certificate to store.
 * @throws KeyStoreException
 */
@Override
public void engineSetCertificateEntry(String alias, Certificate certificate) throws KeyStoreException {

    if (!(certificate instanceof X509Certificate)) {
        throw new KeyStoreException("Certificate must be instance of X509Certificate");
    }
    File file;
    ResourceTrustAnchor trustAnchor = getCertificateEntry(alias);
    if (trustAnchor != null) {
        file = trustAnchor.getFile();
    } else {
        file = new File(defaultDirectory, alias);
    }
    X509Certificate x509Cert = (X509Certificate) certificate;
    try {
        if (!inMemoryOnly) {
            writeCertificate(x509Cert, file);
        }
        ResourceTrustAnchor anchor = new ResourceTrustAnchor(inMemoryOnly,
                new GlobusResource(file.getAbsolutePath()), new TrustAnchor(x509Cert, null));
        this.aliasObjectMap.put(alias, anchor);
        this.certFilenameMap.put(x509Cert, alias);
    } catch (ResourceStoreException e) {
        throw new KeyStoreException(e);
    } catch (IOException e) {
        throw new KeyStoreException(e);
    } catch (CertificateEncodingException e) {
        throw new KeyStoreException(e);
    }
}

From source file:org.jenkins_ci.update_center.Main.java

/**
 * Loads a certificate chain and makes sure it's valid.
 *//* www  . j a v a  2s .c  om*/
protected List<X509Certificate> getCertificateChain() throws IOException, GeneralSecurityException {
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    for (File f : certificates) {
        certs.add(loadCertificate(cf, f));
    }

    Set<TrustAnchor> rootCAs = CertificateUtil.getDefaultRootCAs();
    InputStream stream = getClass().getResourceAsStream("/hudson-community.cert");
    try {
        rootCAs.add(new TrustAnchor((X509Certificate) cf.generateCertificate(stream), null));
    } finally {
        IOUtils.closeQuietly(stream);
    }
    for (File f : rootCA) {
        rootCAs.add(new TrustAnchor(loadCertificate(cf, f), null));
    }

    try {
        CertificateUtil.validatePath(certs, rootCAs);
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }
    return certs;
}

From source file:org.josso.auth.scheme.validation.AbstractX509CertificateValidator.java

/**
  * Initialize the keystore and trusted certificates.
  *///from ww  w .j a va2s.  c om
public synchronized void initialize() {
    try {
        if (_initialized) {
            return;
        }
        if (_trustStore == null) {
            log.error("TrustStore is not set!");
            throw new RuntimeException("Can't initialize keystore!");
        }
        if (_trustAnchorCertAliases == null || _trustAnchorCertAliases.size() == 0) {
            log.error("Trust anchor certificate aliases are not set!");
            throw new RuntimeException("Trust anchor certificate aliases are not set!");
        }

        // load keystore
        _keystore = KeyStore.getInstance("JKS");
        char[] trustPass = null;
        if (_trustPassword != null) {
            trustPass = _trustPassword.toCharArray();
        }
        _keystore.load(getClass().getResourceAsStream(_trustStore), trustPass);

        // load trust anchor certificates
        _trustAnchors = new HashSet<TrustAnchor>();
        for (String trustAnchorCertAlias : _trustAnchorCertAliases) {
            Certificate certificate = _keystore.getCertificate(trustAnchorCertAlias);
            if (certificate != null && certificate instanceof X509Certificate) {
                TrustAnchor ta = new TrustAnchor((X509Certificate) certificate, null);
                _trustAnchors.add(ta);
            }
        }

        // load intermediate CA certificates
        _caCerts = new ArrayList<X509Certificate>();
        if (_caCertAliases != null && _caCertAliases.size() > 0) {
            for (String caCertAlias : _caCertAliases) {
                Certificate certificate = _keystore.getCertificate(caCertAlias);
                if (certificate != null && certificate instanceof X509Certificate) {
                    _caCerts.add((X509Certificate) certificate);
                }
            }
        }

        _initialized = true;

    } catch (Exception e) {
        log.error(e, e);
        throw new RuntimeException("Can't initialize keystore : " + e.getMessage(), e);
    }
}

From source file:org.jvnet.hudson.update_center.Main.java

/**
 * Loads a certificate chain and makes sure it's valid.
 *//*from  www  .j  a v  a  2s .c  o  m*/
protected List<X509Certificate> getCertificateChain() throws IOException, GeneralSecurityException {
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    for (File f : certificates) {
        X509Certificate c = loadCertificate(cf, f);
        c.checkValidity(new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30)));
        certs.add(c);
    }

    Set<TrustAnchor> rootCAs = CertificateUtil.getDefaultRootCAs();
    rootCAs.add(new TrustAnchor(
            (X509Certificate) cf.generateCertificate(getClass().getResourceAsStream("/hudson-community.cert")),
            null));
    for (File f : rootCA) {
        rootCAs.add(new TrustAnchor(loadCertificate(cf, f), null));
    }

    try {
        CertificateUtil.validatePath(certs, rootCAs);
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }
    return certs;
}

From source file:org.jvnet.hudson.update_center.Signing.java

/**
* Loads a certificate chain and makes sure it's valid.
*//*from   w  w  w .ja va2  s.c o  m*/
private List<X509Certificate> getCertificateChain() throws FileNotFoundException, GeneralSecurityException {
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    for (File f : certificates) {
        X509Certificate c = (X509Certificate) cf.generateCertificate(new FileInputStream(f));
        c.checkValidity();
        certs.add(c);
    }

    Set<TrustAnchor> rootCAs = CertificateUtil.getDefaultRootCAs();
    rootCAs.add(new TrustAnchor(
            (X509Certificate) cf.generateCertificate(getClass().getResourceAsStream("/hudson-community.cert")),
            null));

    try {
        CertificateUtil.validatePath(certs, rootCAs);
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }
    return certs;
}

From source file:org.texai.x509.X509Utils.java

/** Validates the given X.509 certificate path, throwing an exception if the path is invalid.
 *
 * @param certPath the given X.509 certificate path, which does not include the trust anchor in contrast to a
 * certificate chain that does// w  w  w  . j a v a2s  .  co  m
 *
 * @throws InvalidAlgorithmParameterException if an invalid certificate path validation parameter is provided
 * @throws NoSuchAlgorithmException if an invalid encryption algorithm is specified
 * @throws CertPathValidatorException if the given x.509 certificate path is invalid
 */
public static void validateCertificatePath(final CertPath certPath)
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, CertPathValidatorException {
    //Preconditions
    assert certPath != null : "certPath must not be null";

    final Set<TrustAnchor> trustAnchors = new HashSet<>();
    trustAnchors.add(new TrustAnchor(X509Utils.getRootX509Certificate(), null)); // nameConstraints
    final PKIXParameters params = new PKIXParameters(trustAnchors);
    params.setSigProvider(BOUNCY_CASTLE_PROVIDER);
    params.setRevocationEnabled(false);
    final CertPathValidator certPathValidator = CertPathValidator
            .getInstance(CertPathValidator.getDefaultType());
    certPathValidator.validate(certPath, params);
}

From source file:org.viafirma.nucleo.validacion.KeyStoreLoader.java

/**
 * Generate a collection of trust anchors representing specified
 * certificates, using specified nameConstraints.
 * //  ww  w .ja  va  2s . c o m
 * @param certs
 *            certificates
 * @param nameConstraints
 *            a byte array containing the ASN.1 DER encoding of a
 *            NameConstraints extension to be used for checking name
 *            constraints.
 * @return trust anchors representing the certificates
 */
@SuppressWarnings("unchecked")
private static Set<TrustAnchor> createTrustAnchors(Collection certs, byte[] nameConstraints) {
    Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(certs.size());
    for (Iterator i = certs.iterator(); i.hasNext();) {
        Certificate cert = (Certificate) i.next();
        if (cert instanceof X509Certificate) {
            anchors.add(new TrustAnchor((X509Certificate) cert, nameConstraints));
        }
    }
    return anchors;
}

From source file:org.votingsystem.web.ejb.SignatureBean.java

public void init() throws Exception {
    Properties properties = new Properties();
    URL res = Thread.currentThread().getContextClassLoader().getResource("KeyStore.properties");
    log.info("init - res: " + res.toURI());
    properties.load(res.openStream());//ww  w  .  j  a v a  2s .co  m
    keyAlias = properties.getProperty("vs.signKeyAlias");
    password = properties.getProperty("vs.signKeyPassword");
    String keyStoreFileName = properties.getProperty("vs.keyStoreFile");
    res = Thread.currentThread().getContextClassLoader().getResource(keyStoreFileName);
    File keyStoreFile = FileUtils.getFileFromBytes(IOUtils.toByteArray(res.openStream()));
    signedMailGenerator = new SMIMESignedGeneratorVS(FileUtils.getBytesFromFile(keyStoreFile), keyAlias,
            password.toCharArray(), ContextVS.SIGN_MECHANISM);
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(keyStoreFile), password.toCharArray());
    certChain = new ArrayList<>();
    for (java.security.cert.Certificate certificate : keyStore.getCertificateChain(keyAlias)) {
        checkAuthorityCertDB((X509Certificate) certificate);
        certChain.add((X509Certificate) certificate);
    }
    keyStorePEMCerts = CertUtils.getPEMEncoded(certChain);
    localServerCertSigner = (X509Certificate) keyStore.getCertificate(keyAlias);
    currencyAnchors = new HashSet<>();
    currencyAnchors.add(new TrustAnchor(localServerCertSigner, null));
    Query query = dao.getEM().createNamedQuery("findCertBySerialNumber").setParameter("serialNumber",
            localServerCertSigner.getSerialNumber().longValue());
    serverCertificateVS = dao.getSingleResult(CertificateVS.class, query);
    serverPrivateKey = (PrivateKey) keyStore.getKey(keyAlias, password.toCharArray());
    encryptor = new Encryptor(localServerCertSigner, serverPrivateKey);
    serverName = config.getServerName();
}

From source file:org.votingsystem.web.ejb.SignatureBean.java

public void addCertAuthority(CertificateVS certificateVS) throws Exception {
    X509Certificate x509Cert = certificateVS.getX509Cert();
    trustedCerts.add(x509Cert);/*from   w ww . j  a va2s  .  c  om*/
    trustedCertsHashMap.put(x509Cert.getSerialNumber().longValue(), certificateVS);
    trustAnchors.add(new TrustAnchor(x509Cert, null));
    log.info("certificateVS.id: " + certificateVS.getId() + " - " + x509Cert.getSubjectDN()
            + " - num. trustedCerts: " + trustedCerts.size());
}