Example usage for java.security.cert CertificateFactory getInstance

List of usage examples for java.security.cert CertificateFactory getInstance

Introduction

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

Prototype

public static final CertificateFactory getInstance(String type) throws CertificateException 

Source Link

Document

Returns a certificate factory object that implements the specified certificate type.

Usage

From source file:org.atricore.idbus.capabilities.clientcertauthn.X509CertificateAuthScheme.java

private X509Certificate buildX509Certificate(byte[] binaryCert) {
    X509Certificate cert = null;/*from www .j  a va 2 s.  c  o  m*/

    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(binaryCert);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        cert = (X509Certificate) cf.generateCertificate(bais);

        if (logger.isDebugEnabled())
            logger.debug("Building X.509 certificate result :\n " + cert);

    } catch (CertificateException ce) {
        logger.error("Error instantiating X.509 Certificate", ce);
    }

    return cert;
}

From source file:com.microsoft.tfs.core.config.httpclient.internal.DefaultX509TrustManager.java

/**
 * Opens the specified resource and returns the data contained as an
 * {@link X509Certificate}. If the resource could not be loaded or could not
 * be converted to an {@link X509Certificate}, then <code>null</code> is
 * returned./*from   w  w w.ja  va2 s  .c  o m*/
 *
 * @param resource
 *        The resource path to open
 */
private static X509Certificate loadResourceAsX509Certificate(final String resource) {
    CertificateFactory certificateFactory;

    try {
        certificateFactory = CertificateFactory.getInstance("X.509"); //$NON-NLS-1$
    } catch (final Exception e) {
        log.warn("Could not load X509 certificate factory", e); //$NON-NLS-1$
        return null;
    }

    final InputStream certificateStream = DefaultX509TrustManager.class.getResourceAsStream(resource);

    if (certificateStream == null) {
        log.warn(MessageFormat.format("Could not load X509 certificate from {0}", resource)); //$NON-NLS-1$
        return null;
    }

    try {
        final Certificate certificate = certificateFactory.generateCertificate(certificateStream);

        if (certificate != null && certificate instanceof X509Certificate) {
            return (X509Certificate) certificate;
        } else {
            log.warn(MessageFormat.format("Could not generate X509 certificate from {0}", resource)); //$NON-NLS-1$
        }
    } catch (final CertificateException e) {
        log.warn(MessageFormat.format("Could not generate X509 certificate from {0}", resource), e); //$NON-NLS-1$
    }

    return null;
}

From source file:net.sf.dsig.verify.X509CRLHelper.java

/**
 * Retrieve the CRL/*from w w  w  .j  a va 2 s  .  co m*/
 * 
 * @param distributionPointUriAsString the distribution point URI
 * @return the {@link X509CRL} object
 * @throws NetworkAccessException when any network access issues occur
 * @throws VerificationException when an error occurs while parsing the CRL
 */
public X509CRL getX509CRL(String distributionPointUriAsString)
        throws NetworkAccessException, VerificationException {
    synchronized (mutex) {
        Date nextUpdate = (Date) uriNextUpdateMap.get(distributionPointUriAsString);
        if (nextUpdate != null && nextUpdate.after(new Date())) {
            logger.debug("Returning cached X509CRL" + "; distributionPoint=" + distributionPointUriAsString
                    + ", nextUpdate=" + nextUpdate);
            return (X509CRL) uriX509CrlMap.get(distributionPointUriAsString);
        }

        HostConfiguration config = getHostConfiguration();

        GetMethod get = new GetMethod(distributionPointUriAsString);
        try {
            getHttpClient().executeMethod(config, get);

            logger.debug("HTTP GET executed" + "; distributionPointUri=" + distributionPointUriAsString
                    + ", statusLine=" + get.getStatusLine());

            if (get.getStatusCode() != HttpStatus.SC_OK) {
                throw new NetworkAccessException("HTTP GET failed; statusLine=" + get.getStatusLine());
            }

            X509CRL crl = null;
            byte[] responseBodyBytes = get.getResponseBody();
            try {
                crl = (X509CRL) CertificateFactory.getInstance("X.509")
                        .generateCRL(new ByteArrayInputStream(responseBodyBytes));
            } catch (CertificateException e) {
                throw new ConfigurationException("X.509 certificate factory missing");
            }

            uriNextUpdateMap.put(distributionPointUriAsString, crl.getNextUpdate());
            uriX509CrlMap.put(distributionPointUriAsString, crl);

            return crl;
        } catch (IOException e) {
            throw new NetworkAccessException("I/O error occured", e);
        } catch (CRLException e) {
            throw new VerificationException("Error while following CRL protocol", e);
        } finally {
            get.releaseConnection();
        }
    }
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplTest.java

/**
 * @throws java.lang.Exception//from   www . j  a va2s.c o m
 */
@BeforeClass
public static void setUpBeforeClass() throws Exception {

    // Just in case, add the BouncyCastle provider
    // It gets added from the CredentialManagerImpl constructor as well
    // but we may need some crypto operations before we invoke the Cred. Manager 
    Security.addProvider(new BouncyCastleProvider());

    // Create a test username and password for a service
    serviceURI = new URI("http://someservice");
    usernamePassword = new UsernamePassword("testuser", "testpasswd");

    // Load the test private key and its certificate
    File privateKeyCertFile = new File(privateKeyFileURL.getPath());
    KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!!
    FileInputStream inStream = new FileInputStream(privateKeyCertFile);
    pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray());
    // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword);
    Enumeration<String> aliases = pkcs12Keystore.aliases();
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        String alias = aliases.nextElement();
        if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry?
            privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias);
            break;
        }
    }
    inStream.close();

    // Load the test trusted certificate (belonging to *.Google.com)
    File trustedCertFile = new File(trustedCertficateFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile);
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    trustedCertficate = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }

    keystoreChangedObserver = new Observer<KeystoreChangedEvent>() {
        @Override
        public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message)
                throws Exception {
            // TODO Auto-generated method stub
        }
    };
}

From source file:be.solidx.hot.nio.http.SSLContextBuilder.java

private TrustManager[] handleTrustManagers(Map<String, Object> options)
        throws CertificateException, IOException, URISyntaxException {
    boolean rejectUnauthorized = (boolean) options.get(REJECTUNAUTHORIZED);
    if (options.get(CA) != null) {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        return new TrustManager[] { new TrustManager(
                (X509Certificate) certificateFactory
                        .generateCertificate(getInputStream(new URI(options.get(CA).toString()))),
                rejectUnauthorized) };//from  www. j  a v a 2 s .com
    } else if (!rejectUnauthorized) {
        return new TrustManager[] { new TrustManager(null, rejectUnauthorized) };
    }
    return null;
}

From source file:org.globus.gsi.trustmanager.TrustedCertPathFinder.java

/**
 * Method that validates the provided cert path to find a trusted certificate in the certificate store.
 * <p/>/*www.j  a  v  a2s  .  c o  m*/
 * For each certificate i in certPath, it is expected that the i+1 certificate is the issuer of the certificate
 * path. See CertPath.
 * <p/>
 * For each certificate i in certpath, validate signature of certificate i get issuer of certificate i get
 * certificate i+i ensure that the certificate i+1 is issuer of certificate i If not, throw an exception for
 * illegal argument validate signature of i+1 Throw exception if it does not validate check if i+1 is a trusted
 * certificate in the trust store. If so return certpath until i+1 If not, continue; If all certificates in the
 * certpath have been checked and none exisits in trust store, check if trust store has certificate of issuer of
 * last certificate in CertPath. If so, return certPath + trusted certificate from trust store If not, throw
 * an exception for lack of valid trust root.
 *
 * @param keyStore The key store containing CA trust root certificates
 * @param certPath The certpath from which to extract a valid cert path to a trusted certificate.
 * @return The valid CertPath.
 * @throws CertPathValidatorException If the CertPath is invalid.
 */
public static CertPath findTrustedCertPath(KeyStore keyStore, CertPath certPath)
        throws CertPathValidatorException {

    // This will be the cert path to return
    List<X509Certificate> trustedCertPath = new ArrayList<X509Certificate>();
    // This is the certs to validate
    List<? extends Certificate> certs = certPath.getCertificates();

    X509Certificate x509Certificate;
    int index = 0;
    int certsSize = certs.size();

    Certificate certificate = certs.get(index);
    if (!(certificate instanceof X509Certificate)) {
        throw new CertPathValidatorException(
                "Certificate of type " + X509Certificate.class.getName() + " required");
    }
    x509Certificate = (X509Certificate) certificate;

    while (index < certsSize) {
        CertPath finalCertPath = isTrustedCert(keyStore, x509Certificate, trustedCertPath);
        if (finalCertPath != null) {
            return finalCertPath;
        }

        if (index + 1 >= certsSize) {
            break;
        }

        index++;
        Certificate issuerCertificate = certs.get(index);
        x509Certificate = checkCertificate(trustedCertPath, x509Certificate, issuerCertificate);
    }

    X509CertSelector selector = new X509CertSelector();
    selector.setSubject(x509Certificate.getIssuerX500Principal());
    Collection<? extends Certificate> caCerts;
    try {
        caCerts = KeyStoreUtil.getTrustedCertificates(keyStore, selector);
    } catch (KeyStoreException e) {
        throw new CertPathValidatorException(e);
    }
    if (caCerts.size() < 1) {
        throw new CertPathValidatorException("No trusted path can be constructed");
    }

    boolean foundTrustRoot = false;

    for (Certificate caCert : caCerts) {
        if (!(caCert instanceof X509Certificate)) {
            logger.warn("Skipped a certificate: not an X509Certificate");
            continue;
        }
        try {
            trustedCertPath.add(checkCertificate(trustedCertPath, x509Certificate, caCert));
            // currently the caCert self-signature is not checked
            // to be consistent with the isTrustedCert() method
            foundTrustRoot = true;
            // we found a CA cert that signed the certificate
            // so we don't need to check any more
            break;
        } catch (CertPathValidatorException e) {
            // fine, just move on to check the next potential CA cert
            // after the loop we'll check whether any were successful
            logger.warn("Failed to validate signature of certificate with " + "subject DN '"
                    + x509Certificate.getSubjectDN() + "' against a CA certificate with issuer DN '"
                    + ((X509Certificate) caCert).getSubjectDN() + "'");
        }
    }

    if (!foundTrustRoot) {
        throw new CertPathValidatorException("No trusted path can be constructed");
    }

    try {
        CertificateFactory certFac = CertificateFactory.getInstance("X.509");
        return certFac.generateCertPath(trustedCertPath);
    } catch (CertificateException e) {
        throw new CertPathValidatorException("Error generating trusted certificate path", e);
    }
}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoCertificateService.java

/**
 * Parses a X.509 certificate from a PEM certificate string
 *
 * @param certString/*from  ww  w  .  ja  v a2s. c om*/
 * @return
 * @throws CertificateException
 */
public X509Certificate parseCertificate(String certString) throws CertificateException {
    CertificateFactory fac = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream stream = new ByteArrayInputStream(certString.getBytes());
    Certificate cert = fac.generateCertificate(stream);
    if (cert instanceof X509Certificate) {
        return (X509Certificate) cert;
    } else {
        throw new IllegalArgumentException("Provided certificate did not parse as a X509 certificate");
    }
}

From source file:jenkins.plugins.publish_over_ftp.BapFtpHostConfiguration.java

public FTPClient createFTPClient() throws GeneralSecurityException, FileNotFoundException, IOException {
    if (useFtpOverTls) {
        FTPSClient c = new FTPSClient(false);

        KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
        String trustStorePath = System.getProperty("javax.net.ssl.trustStore");
        if (trustStorePath != null) {
            String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
            if (trustStorePassword != null) {
                ts.load(new FileInputStream(trustStorePath), trustStorePassword.toCharArray());
            } else {
                ts.load(new FileInputStream(trustStorePath), null);
            }// w  ww.j  a v a 2  s.  co  m
        } else {
            ts.load(null);
        }

        if (trustedCertificate != null) {
            InputStream certStream = new ByteArrayInputStream(trustedCertificate.getBytes());
            X509Certificate x509certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
                    .generateCertificate(certStream);
            ts.setCertificateEntry(x509certificate.getSubjectDN().getName(), x509certificate);
        }

        c.setTrustManager(TrustManagerUtils.getDefaultTrustManager(ts));

        return c;
    }
    return new FTPClient();
}

From source file:com.vmware.identity.openidconnect.server.LoginProcessor.java

private PersonUser processPersonUserCertificateLogin() throws LoginException {
    if (this.httpRequest
            .getCookieValue(SessionManager.getPersonUserCertificateLoggedOutCookieName(this.tenant)) != null) {
        throw new LoginException("already logged in once on this browser session",
                localize(ErrorMessage.LOGGED_OUT_TLS_SESSION));
    }//  ww  w  . j av  a2s. c  o  m

    List<X509Certificate> personUserCertificateChain;

    String certString64 = this.httpRequest.getHeaderValue("X-SSL-Client-Certificate");

    if (!StringUtils.isEmpty(certString64)) {
        byte[] certBytes = Base64Utils.decodeToBytes(certString64);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(certBytes);
        try {
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) certFactory.generateCertificate(inputStream);
            personUserCertificateChain = Arrays.asList(cert);
        } catch (CertificateException e) {
            throw new LoginException("failed to parse person user cert",
                    localize(ErrorMessage.INVALID_CREDENTIAL), e);
        }
    } else {
        personUserCertificateChain = this.httpRequest.getClientCertificateChain();
        if (personUserCertificateChain == null || personUserCertificateChain.size() == 0) {
            throw new LoginException("missing person user cert", localize(ErrorMessage.NO_CLIENT_CERT));
        }
    }

    try {
        return this.personUserAuthenticator.authenticateByPersonUserCertificate(this.tenant,
                personUserCertificateChain);
    } catch (InvalidCredentialsException e) {
        throw new LoginException("invalid person user cert", localize(ErrorMessage.INVALID_CREDENTIAL), e);
    } catch (ServerException e) {
        throw new LoginException("error while authenticating person user cert",
                localize(ErrorMessage.RESPONDER), e);
    }
}