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, Provider provider) throws CertificateException 

Source Link

Document

Returns a certificate factory object for the specified certificate type.

Usage

From source file:be.fedict.trust.crl.OnlineCrlRepository.java

private X509CRL getCrl(URI crlUri) throws IOException, CertificateException, CRLException,
        NoSuchProviderException, NoSuchParserException, StreamParsingException {
    HttpClient httpClient = new HttpClient();
    if (null != this.networkConfig) {
        httpClient.getHostConfiguration().setProxy(this.networkConfig.getProxyHost(),
                this.networkConfig.getProxyPort());
    }/*w  w w.  j av a 2s  . c  om*/
    if (null != this.credentials) {
        HttpState httpState = httpClient.getState();
        this.credentials.init(httpState);
    }
    String downloadUrl = crlUri.toURL().toString();
    LOG.debug("downloading CRL from: " + downloadUrl);
    GetMethod getMethod = new GetMethod(downloadUrl);
    getMethod.addRequestHeader("User-Agent", "jTrust CRL Client");
    int statusCode = httpClient.executeMethod(getMethod);
    if (HttpURLConnection.HTTP_OK != statusCode) {
        LOG.debug("HTTP status code: " + statusCode);
        return null;
    }

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
    X509CRL crl = (X509CRL) certificateFactory.generateCRL(getMethod.getResponseBodyAsStream());
    LOG.debug("CRL size: " + crl.getEncoded().length + " bytes");
    return crl;
}

From source file:org.nimbustools.ctxbroker.security.CertificateAuthority.java

/**
 * CertificateAuthority constructor//from   ww w. j a va 2 s  .c  om
 *
 * @param caCert CA's public cert, X509Certificate
 * @param caPrivateKey (unencrypted) private key object
 * @param globusCADN only used for logging
 * @throws NoSuchProviderException problem initializing keypair generator
 * @throws NoSuchAlgorithmException problem initializing keypair generator
 * @throws CertificateException problem initializing certificate factory
 * @throws IOException file/stream problem
 * @throws ContextBrokerException other problem with CA input
 */
protected CertificateAuthority(X509Certificate caCert, PrivateKey caPrivateKey, String globusCADN)
        throws NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException,
        ContextBrokerException {

    if (caCert == null) {
        throw new IllegalArgumentException("caCert is null");
    }

    if (caPrivateKey == null) {
        throw new IllegalArgumentException("caPrivateKey is null");
    }

    this.kpGen = KeyPairGenerator.getInstance("RSA", "BC");
    this.kpGen.initialize(1024, new SecureRandom());

    this.certGen = new X509V3CertificateGenerator();

    this.factory = CertificateFactory.getInstance("X.509", "BC");

    this.caX509 = caCert;
    this.caPrivate = caPrivateKey;

    this.caX509Name = new X509Principal(caX509.getIssuerX500Principal().getEncoded());

    this.initializeGenerator();

    X500Principal subjectDN = caCert.getSubjectX500Principal();

    String targetBase = subjectDN.getName(X500Principal.RFC2253);

    String[] parts = targetBase.split(",");
    String target = "";
    int cnCount = 0;
    for (int i = 0; i < parts.length; i++) {
        String newpiece;
        if (parts[i].startsWith("CN") || parts[i].startsWith("cn")) {
            newpiece = replaceToken;
            cnCount += 1;
        } else {
            newpiece = parts[i];
        }
        if (i == 0) {
            target = newpiece;
        } else {
            target = newpiece + "," + target;
        }
    }

    if (cnCount == 0) {
        throw new ContextBrokerException("Unsupported: CA has no " + "CN (?)");
    }

    if (cnCount != 1) {
        throw new ContextBrokerException("Unsupported: CA has more " + "than one CN");
    }

    this.targetString = target;

    final String msg = "Initialized certificate authority with subject " + "DN (RFC2253) = '" + targetBase
            + "' " + "and Globus style DN = '" + globusCADN + "'. " + "New DNs will look like this (RFC2253): '"
            + this.targetString + "'";

    logger.info(msg);
}

From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java

/**
 * Load one or more certificates from the specified stream.
 *
 * @param is//from  w  w w.ja v  a 2  s.  c o  m
 *            Stream to load certificates from
 * @return The certificates
 * @throws CryptoException
 *             Problem encountered while loading the certificate(s)
 */
public static X509Certificate[] loadCertificates(InputStream is) throws CryptoException {
    byte[] certsBytes = null;

    try {
        certsBytes = ReadUtil.readFully(is);

        // fix common input certificate problems by converting PEM/B64 to DER
        certsBytes = fixCommonInputCertProblems(certsBytes);

        is = new ByteArrayInputStream(certsBytes);

        CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, "GNU-PKI");

        Collection<? extends Certificate> certs = cf.generateCertificates(is);

        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()]);
    } catch (IOException ex) {
        throw new CryptoException(res.getString("NoLoadCertificate.exception.message"), ex);
    } catch (NoSuchProviderException e) {
        throw new CryptoException(res.getString("NoLoadCertificate.exception.message"), e);
    } catch (CertificateException ex) {
        // Failed to load certificates, may be pki path encoded - try loading as that
        try {
            return loadCertificatesPkiPath(new ByteArrayInputStream(certsBytes));
        } catch (CryptoException ex2) {
            throw new CryptoException(res.getString("NoLoadCertificate.exception.message"), ex);
        }
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:org.gluu.oxtrust.ldap.service.SSLService.java

/**
 * Load one or more certificates from the specified byte array.
 *
 * @param certsBytes Byte array to load certificates from
 * @return The array of certificates/*  www .  ja v  a  2  s . c om*/
 */
public static X509Certificate[] loadCertificates(byte[] certsBytes) throws Exception {
    try {
        // fix common input certificate problems by converting PEM/B64 to DER
        certsBytes = fixCommonInputCertProblems(certsBytes);

        CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, SECURITY_PROVIDER_BOUNCY_CASTLE);

        Collection<? extends Certificate> certs = cf.generateCertificates(new ByteArrayInputStream(certsBytes));

        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()]);
    } catch (CertificateException ex) {
        try {
            // Failed to load certificates, may be pki path encoded - try loading as that
            return loadCertificatesAsPkiPathEncoded(new ByteArrayInputStream(certsBytes));
        } catch (CertificateException e) {
            // Failed to load certificates, may be PEM certificate
            X509Certificate certs[] = new X509Certificate[1];
            certs[0] = getPEMCertificateStatic(new ByteArrayInputStream(certsBytes));
            return certs;
        }
    }
}

From source file:org.kse.crypto.x509.X509CertUtil.java

private static X509Certificate[] loadCertificatesPkiPath(InputStream is) throws CryptoException {
    try {//from  w  w  w.  j  av  a2s  . c om
        CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce());
        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()]);
    } catch (CertificateException | NoSuchProviderException e) {
        throw new CryptoException(res.getString("NoLoadPkiPath.exception.message"), e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:org.apache.ws.security.components.crypto.CryptoProviderTest.java

/**
 * Test loading a certificate using BouncyCastle, and using it to encrypt a message, but
 * decrypt the message using the Java Keystore provider
 */// w  ww  . jav a  2s  .co  m
@org.junit.Test
public void testInterop() throws Exception {
    // 
    // This cert corresponds to the cert in wss86.keystore
    // Extracted with:
    // keytool -export -rfc -keystore wss86.keystore -alias wss86 -file wss86.cer
    //
    byte[] certBytes = org.apache.ws.security.util.Base64
            .decode("MIICfDCCAeUCBEnHoGMwDQYJKoZIhvcNAQEEBQAwgYQxCzAJBgNVBAYTAkRFMQ8wDQYDVQQIEwZC"
                    + "YXllcm4xDzANBgNVBAcTBk11bmljaDEPMA0GA1UEChMGQXBhY2hlMQ4wDAYDVQQLEwVXU1M0SjEP"
                    + "MA0GA1UEAxMGV2VybmVyMSEwHwYJKoZIhvcNAQkBFhJXZXJuZXJAZXhhbXBsZS5jb20wHhcNMDkw"
                    + "MzIzMTQ0NDUxWhcNMTkwMzIxMTQ0NDUxWjCBhDELMAkGA1UEBhMCREUxDzANBgNVBAgTBkJheWVy"
                    + "bjEPMA0GA1UEBxMGTXVuaWNoMQ8wDQYDVQQKEwZBcGFjaGUxDjAMBgNVBAsTBVdTUzRKMQ8wDQYD"
                    + "VQQDEwZXZXJuZXIxITAfBgkqhkiG9w0BCQEWEldlcm5lckBleGFtcGxlLmNvbTCBnzANBgkqhkiG"
                    + "9w0BAQEFAAOBjQAwgYkCgYEA3uRplw7q8y/sIR541uCrlbIMzJHXCRU3nQreGNr6dM49/LxHYffQ"
                    + "Ex99chQh+wR6fwArFlziDRNnqslOy8zKMfGbaBaR41ZZrxvkSsIwzOhD6yAPgKVQL2vTmJAbdZ35"
                    + "GwcOW8oe7l+NV9qmv7yrr5OhqDhFh36WhgjVLiwmP/cCAwEAATANBgkqhkiG9w0BAQQFAAOBgQBP"
                    + "PnR2BYn7DKn/SkU8XTgf9g2NoYcMyvQOB+Uo25/QzDdMk6HKmHl0+7mh7RAtXcBz2YqC3WbQW5U3"
                    + "KmOH6fVxB8hw6xalBjs2YpnBx4gaHAws35KlAfkGVVe5wqnrI7ER7RBYO/7Gr7uCUq11QrGyEG8/"
                    + "yIXktaFLxgD2R4hpfA==");
    CertificateFactory factory = CertificateFactory.getInstance("X.509", "BC");
    X509Certificate cert = (X509Certificate) factory
            .generateCertificate(new java.io.ByteArrayInputStream(certBytes));

    WSSecEncrypt encrypt = new WSSecEncrypt();
    encrypt.setUseThisCert(cert);
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Document encryptedDoc = encrypt.build(doc, crypto, secHeader);

    if (LOG.isDebugEnabled()) {
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
        LOG.debug(outputString);
    }
    verify(encryptedDoc);

}

From source file:edu.ucsb.eucalyptus.keys.AbstractKeyStore.java

public static X509Certificate pemToX509(final String certPem)
        throws CertificateException, NoSuchProviderException {
    CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509", KeyTool.PROVIDER);
    X509Certificate cert = (X509Certificate) certificatefactory
            .generateCertificate(new ByteArrayInputStream(certPem.getBytes()));
    return cert;//from   w  ww.  java2  s.  co  m
}

From source file:cn.mrdear.pay.util.RSAUtils.java

/**
 * ??//ww w .j  a va2s.  com
 * 
 * @param type
 *            
 * @param inputStream
 *            ?
 * @return ?
 */
public static Certificate getCertificate(String type, InputStream inputStream) {
    Assert.isNotEmpty(type);
    Assert.notNull(inputStream);

    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance(type, PROVIDER);
        return certificateFactory.generateCertificate(inputStream);
    } catch (CertificateException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:org.gluu.oxtrust.ldap.service.SSLService.java

private static X509Certificate[] loadCertificatesAsPkiPathEncoded(InputStream is) throws Exception {
    try {//from ww w.  ja v a 2s. c om
        CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, SECURITY_PROVIDER_BOUNCY_CASTLE);
        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);
    }
}