Example usage for java.security.cert CertificateFactory generateCertificate

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

Introduction

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

Prototype

public final Certificate generateCertificate(InputStream inStream) throws CertificateException 

Source Link

Document

Generates a certificate object and initializes it with the data read from the input stream inStream .

Usage

From source file:io.personium.common.auth.token.TransCellAccessToken.java

/**
 * X509??./*from  w  ww.  j  av a2 s  .c  o m*/
 * @param privateKeyFileName ???
 * @param certificateFileName ??
 * @param rootCertificateFileNames ??
 * @throws IOException IOException
 * @throws NoSuchAlgorithmException NoSuchAlgorithmException
 * @throws InvalidKeySpecException InvalidKeySpecException
 * @throws CertificateException CertificateException
 * @throws InvalidNameException InvalidNameException
 */
public static void configureX509(String privateKeyFileName, String certificateFileName,
        String[] rootCertificateFileNames) throws IOException, NoSuchAlgorithmException,
        InvalidKeySpecException, CertificateException, InvalidNameException {

    xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");

    // Read RootCA Certificate
    x509RootCertificateFileNames = new ArrayList<String>();
    if (rootCertificateFileNames != null) {
        for (String fileName : rootCertificateFileNames) {
            x509RootCertificateFileNames.add(fileName);
        }
    }

    // Read Private Key
    InputStream is = null;
    if (privateKeyFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_KEY_PATH);
    } else {
        is = new FileInputStream(privateKeyFileName);
    }

    PEMReader privateKeyPemReader = new PEMReader(is);
    byte[] privateKeyDerBytes = privateKeyPemReader.getDerBytes();
    PKCS1EncodedKeySpec keySpecRSAPrivateKey = new PKCS1EncodedKeySpec(privateKeyDerBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    privKey = keyFactory.generatePrivate(keySpecRSAPrivateKey.getKeySpec());

    // Read Certificate
    if (certificateFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_CRT_PATH);
    } else {
        is = new FileInputStream(certificateFileName);
    }
    PEMReader serverCertificatePemReader;
    serverCertificatePemReader = new PEMReader(is);
    byte[] serverCertificateBytesCert = serverCertificatePemReader.getDerBytes();
    CertificateFactory cf = CertificateFactory.getInstance(X509KeySelector.X509KEY_TYPE);
    x509Certificate = (X509Certificate) cf
            .generateCertificate(new ByteArrayInputStream(serverCertificateBytesCert));

    // Create the KeyInfo containing the X509Data
    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    List x509Content = new ArrayList();
    x509Content.add(x509Certificate.getSubjectX500Principal().getName());
    x509Content.add(x509Certificate);
    X509Data xd = keyInfoFactory.newX509Data(x509Content);
    keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(xd));

    // Get FQDN from Certificate and set FQDN to PersoniumCoreUtils
    String dn = x509Certificate.getSubjectX500Principal().getName();
    LdapName ln = new LdapName(dn);
    for (Rdn rdn : ln.getRdns()) {
        if (rdn.getType().equalsIgnoreCase("CN")) {
            PersoniumCoreUtils.setFQDN(rdn.getValue().toString());
            break;
        }
    }

    // http://java.sun.com/developer/technicalArticles/xml/dig_signature_api/

}

From source file:com.aware.ui.Plugins_Manager.java

/**
* Downloads and compresses image for optimized icon caching
* @param image_url//from w  w w  . j a  va  2s.  c om
* @return
*/
public static byte[] cacheImage(String image_url, Context sContext) {
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = sContext.getResources().openRawResource(R.raw.aware);
        Certificate ca;
        try {
            ca = cf.generateCertificate(caInput);
        } finally {
            caInput.close();
        }

        KeyStore sKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream inStream = sContext.getResources().openRawResource(R.raw.awareframework);
        sKeyStore.load(inStream, "awareframework".toCharArray());
        inStream.close();

        sKeyStore.setCertificateEntry("ca", ca);

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(sKeyStore);

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        //Fetch image now that we recognise SSL
        URL image_path = new URL(image_url.replace("http://", "https://")); //make sure we are fetching the images over https
        HttpsURLConnection image_connection = (HttpsURLConnection) image_path.openConnection();
        image_connection.setSSLSocketFactory(context.getSocketFactory());

        InputStream in_stream = image_connection.getInputStream();
        Bitmap tmpBitmap = BitmapFactory.decodeStream(in_stream);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        tmpBitmap.compress(Bitmap.CompressFormat.PNG, 100, output);

        return output.toByteArray();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.apache.ofbiz.base.util.KeyStoreUtil.java

public static void importPKCS8CertChain(KeyStore ks, String alias, byte[] keyBytes, String keyPass,
        byte[] certChain)
        throws InvalidKeySpecException, NoSuchAlgorithmException, CertificateException, KeyStoreException {
    // load the private key
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyBytes);
    PrivateKey pk = kf.generatePrivate(keysp);

    // load the cert chain
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bais = new ByteArrayInputStream(certChain);

    Collection<? extends Certificate> certCol = cf.generateCertificates(bais);
    Certificate[] certs = new Certificate[certCol.toArray().length];
    if (certCol.size() == 1) {
        Debug.logInfo("Single certificate; no chain", module);
        bais = new ByteArrayInputStream(certChain);
        Certificate cert = cf.generateCertificate(bais);
        certs[0] = cert;/*from w w  w . j  a  v  a  2  s  . co m*/
    } else {
        Debug.logInfo("Certificate chain length : " + certCol.size(), module);
        certs = certCol.toArray(new Certificate[certCol.size()]);
    }

    ks.setKeyEntry(alias, pk, keyPass.toCharArray(), certs);
}

From source file:net.sf.jsignpdf.utils.KeyStoreUtils.java

/**
 * Loads a {@link X509Certificate} from the given path. Returns null if the
 * certificate can't be loaded./*w  w w  . ja  va  2s  .  c  o  m*/
 * 
 * @param filePath
 * @return
 */
public static X509Certificate loadCertificate(final String filePath) {
    if (StringUtils.isEmpty(filePath)) {
        LOGGER.debug("Empty file path");
        return null;
    }
    FileInputStream inStream = null;
    X509Certificate cert = null;
    try {
        final CertificateFactory certFac = CertificateFactory.getInstance(Constants.CERT_TYPE_X509); // X.509
        inStream = FileUtils.openInputStream(new File(filePath));
        cert = (X509Certificate) certFac.generateCertificate(inStream);
    } catch (Exception e) {
        LOGGER.debug("Unable to load certificate", e);
    } finally {
        IOUtils.closeQuietly(inStream);
    }
    return cert;
}

From source file:org.bankinterface.util.KeyStoreUtil.java

public static void importPKCS8CertChain(KeyStore ks, String alias, byte[] keyBytes, String keyPass,
        byte[] certChain)
        throws InvalidKeySpecException, NoSuchAlgorithmException, CertificateException, KeyStoreException {
    // load the private key
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyBytes);
    PrivateKey pk = kf.generatePrivate(keysp);

    // load the cert chain
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bais = new ByteArrayInputStream(certChain);

    Collection<? extends Certificate> certCol = cf.generateCertificates(bais);
    Certificate[] certs = new Certificate[certCol.toArray().length];
    if (certCol.size() == 1) {
        logger.info("Single certificate; no chain");
        bais = new ByteArrayInputStream(certChain);
        Certificate cert = cf.generateCertificate(bais);
        certs[0] = cert;//from w  ww  . java 2s. c  o m
    } else {
        logger.info("Certificate chain length : " + certCol.size());
        certs = certCol.toArray(new Certificate[certCol.size()]);
    }

    ks.setKeyEntry(alias, pk, keyPass.toCharArray(), certs);
}

From source file:org.exoplatform.services.videocall.AuthService.java

protected static TrustManager[] getTrustManagers(InputStream trustStoreFile, String trustStorePassword)
        throws Exception {
    CertificateFactory certificateFactory = null;
    try {//  w w  w. ja  v a2s .co  m
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not initialize the certificate " + e.getMessage());
        }
    }

    Certificate caCert = null;
    try {
        caCert = certificateFactory.generateCertificate(trustStoreFile);
    } catch (CertificateException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Bad key or certificate in " + trustStoreFile, e.getMessage());
        }
    }

    KeyStore trustStore = null;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
    } catch (KeyStoreException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Java implementation cannot manipulate " + KeyStore.getDefaultType() + " keystores");
        }
    } catch (NoSuchAlgorithmException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not initialize truststore ", e);
        }
    } catch (CertificateException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not initialize truststore ", e);
        }
    } catch (IOException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not initialize truststore ", e);
        }
    }

    try {
        trustStore.setCertificateEntry("CA", caCert);
    } catch (KeyStoreException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error(trustStoreFile + " cannot be used as a CA", e);
        }
    }

    TrustManagerFactory tmf = null;
    try {
        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
    } catch (NoSuchAlgorithmException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Java implementation cannot manipulate " + KeyStore.getDefaultType() + " trusts", e);
        }
    } catch (KeyStoreException e) {
        LOG.error("Java implementation cannot manipulate " + KeyStore.getDefaultType() + " trusts", e);
    }
    return tmf.getTrustManagers();
}

From source file:be.fedict.eid.tsl.BelgianTrustServiceListFactory.java

private static X509Certificate loadCertificateFromResource(String resourceName) {
    Thread currentThread = Thread.currentThread();
    ClassLoader classLoader = currentThread.getContextClassLoader();
    InputStream certificateInputStream = classLoader.getResourceAsStream(resourceName);
    if (null == certificateInputStream) {
        throw new IllegalArgumentException("could not load certificate resource: " + resourceName);
    }/*  ww  w .j  a va  2 s  .  c o m*/
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(certificateInputStream);
        return certificate;
    } catch (CertificateException e) {
        throw new RuntimeException("certificate factory error: " + e.getMessage(), e);
    }
}

From source file:org.apache.nifi.registry.security.util.CertificateUtils.java

private static X509Certificate formX509Certificate(byte[] encodedCertificate) throws CertificateException {
    try {//w  ww  . j a v a  2 s .c  o  m
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream bais = new ByteArrayInputStream(encodedCertificate);
        return (X509Certificate) cf.generateCertificate(bais);
    } catch (CertificateException e) {
        logger.error("Error converting the certificate", e);
        throw e;
    }
}

From source file:com.guster.skywebservice.library.webservice.SkyHttp.java

public static void setSSLCertificate(InputStream certificateFile) throws CertificateException, IOException,
        KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate cert = cf.generateCertificate(certificateFile);

    certificateFile.close();/*from  www .jav a 2 s.  c o m*/

    // create a keystore containing the certificate
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", cert);

    // create a trust manager for our certificate
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);

    // create a SSLContext that uses our trust manager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);

    // set socket factory
    setSSLSocketFactory(context.getSocketFactory());
}

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  ww  w.  j ava2s . c om*/
 *
 * @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;
}