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:nextflow.k8s.client.SSLUtils.java

public static KeyStore createKeyStore(InputStream certInputStream, InputStream keyInputStream,
        String clientKeyAlgo, char[] clientKeyPassphrase, String keyStoreFile, char[] keyStorePassphrase)
        throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException,
        KeyStoreException {/*from   w  ww. jav a2 s .  c  o m*/
    CertificateFactory certFactory = CertificateFactory.getInstance("X509");
    X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream);

    byte[] keyBytes = decodePem(keyInputStream);

    PrivateKey privateKey;

    KeyFactory keyFactory = KeyFactory.getInstance(clientKeyAlgo);
    try {
        // First let's try PKCS8
        privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
    } catch (InvalidKeySpecException e) {
        // Otherwise try PKCS1
        RSAPrivateCrtKeySpec keySpec = decodePKCS1(keyBytes);
        privateKey = keyFactory.generatePrivate(keySpec);
    }

    KeyStore keyStore = KeyStore.getInstance("JKS");
    if (keyStoreFile != null && keyStoreFile.length() > 0) {
        keyStore.load(new FileInputStream(keyStoreFile), keyStorePassphrase);
    } else {
        loadDefaultKeyStoreFile(keyStore, keyStorePassphrase);
    }

    String alias = cert.getSubjectX500Principal().getName();
    keyStore.setKeyEntry(alias, privateKey, clientKeyPassphrase, new Certificate[] { cert });

    return keyStore;
}

From source file:io.kubernetes.client.util.SSLUtils.java

public static KeyStore createKeyStore(InputStream certInputStream, InputStream keyInputStream,
        String clientKeyAlgo, char[] clientKeyPassphrase, String keyStoreFile, char[] keyStorePassphrase)
        throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException,
        KeyStoreException {// w w  w . j a  v a  2 s. c om
    CertificateFactory certFactory = CertificateFactory.getInstance("X509");
    X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream);

    byte[] keyBytes = decodePem(keyInputStream);

    PrivateKey privateKey;

    KeyFactory keyFactory = KeyFactory.getInstance(clientKeyAlgo);
    try {
        // First let's try PKCS8
        privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
    } catch (InvalidKeySpecException e) {
        // Otherwise try PKCS8
        RSAPrivateCrtKeySpec keySpec = decodePKCS1(keyBytes);
        privateKey = keyFactory.generatePrivate(keySpec);
    }

    KeyStore keyStore = KeyStore.getInstance("JKS");
    if (keyStoreFile != null && keyStoreFile.length() > 0) {
        keyStore.load(new FileInputStream(keyStoreFile), keyStorePassphrase);
    } else {
        loadDefaultKeyStoreFile(keyStore, keyStorePassphrase);
    }

    String alias = cert.getSubjectX500Principal().getName();
    keyStore.setKeyEntry(alias, privateKey, clientKeyPassphrase, new Certificate[] { cert });

    return keyStore;
}

From source file:me.xiaopan.android.gohttp.httpclient.MySSLSocketFactory.java

/**
 * Gets a KeyStore containing the Certificate
 *
 * @param cert InputStream of the Certificate
 * @return KeyStore//from   w ww.j a va2 s  .  c  om
 */
public static KeyStore getKeystoreOfCA(InputStream cert) {

    // Load CAs from an InputStream
    InputStream caInput = null;
    Certificate ca = null;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        caInput = new BufferedInputStream(cert);
        ca = (Certificate) cf.generateCertificate(caInput);
    } catch (CertificateException e1) {
        e1.printStackTrace();
    } finally {
        try {
            caInput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = null;
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", (Certificate) ca);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return keyStore;
}

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 w  w  w.  ja  v a2s  .co 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:org.obm.sync.push.client.SSLContextFactoryTest.java

@Test
public void testKeyStoreIsPKCS12() throws Exception {
    InputStream pkcs12Stream = ClassLoader.getSystemClassLoader().getResourceAsStream("pkcs_pwd_toto.p12");
    char[] pkcs12Password = "toto".toCharArray();

    KeyStore keyStore = SSLContextFactory.loadPKCS12KeyStore(pkcs12Stream, pkcs12Password);

    InputStream pkcs12InnerX509 = ClassLoader.getSystemClassLoader().getResourceAsStream("pkcs_inner_x509.crt");
    Certificate pkcs12InnerCertificate = CertificateFactory.getInstance("x509")
            .generateCertificate(pkcs12InnerX509);
    assertThat(keyStore.getType()).isEqualToIgnoringCase("pkcs12");
    assertThat(keyStore.getCertificate("client2")).isEqualTo(pkcs12InnerCertificate);
}

From source file:cn.com.loopj.android.http.MySSLSocketFactory.java

/**
 * Gets a KeyStore containing the Certificate
 *
 * @param cert InputStream of the Certificate
 * @return KeyStore/*from   w w  w. j av a  2  s  .  com*/
 */
public static KeyStore getKeystoreOfCA(InputStream cert) {

    // Load CAs from an InputStream
    InputStream caInput = null;
    Certificate ca = null;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        caInput = new BufferedInputStream(cert);
        ca = cf.generateCertificate(caInput);
    } catch (CertificateException e1) {
        e1.printStackTrace();
    } finally {
        try {
            if (caInput != null) {
                caInput.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = null;
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return keyStore;
}

From source file:com.amazon.alexa.avs.auth.companionservice.CompanionServiceClient.java

/**
 * Loads the CA certificate into an in-memory keystore and creates an {@link SSLSocketFactory}.
 *
 * @return SSLSocketFactory//from  w ww.j  a va 2 s.c o m
 */
public SSLSocketFactory getPinnedSSLSocketFactory() {
    InputStream caCertInputStream = null;
    InputStream clientKeyPair = null;
    try {
        // Load the CA certificate into memory
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        caCertInputStream = new FileInputStream(deviceConfig.getCompanionServiceInfo().getSslCaCert());
        Certificate caCert = cf.generateCertificate(caCertInputStream);

        // Load the CA certificate into the trusted KeyStore
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setCertificateEntry("myca", caCert);

        // Create a TrustManagerFactory with the trusted KeyStore
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        // Load the client certificate and private key into another KeyStore
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        clientKeyPair = new FileInputStream(deviceConfig.getCompanionServiceInfo().getSslClientKeyStore());
        keyStore.load(clientKeyPair,
                deviceConfig.getCompanionServiceInfo().getSslClientKeyStorePassphrase().toCharArray());

        // Create a TrustManagerFactory with the client key pair KeyStore
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore,
                deviceConfig.getCompanionServiceInfo().getSslClientKeyStorePassphrase().toCharArray());

        // Initialize the SSLContext and return an SSLSocketFactory;
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        return sc.getSocketFactory();
    } catch (CertificateException | KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException
            | IOException | KeyManagementException e) {
        throw new RuntimeException("The KeyStore for contacting the Companion Service could not be loaded.", e);
    } finally {
        IOUtils.closeQuietly(caCertInputStream);
        IOUtils.closeQuietly(clientKeyPair);
    }
}

From source file:com.google.u2f.gaedemo.storage.TokenStorageData.java

private static X509Certificate parseCertificate(byte[] encodedDerCertificate) {
    try {//from   w w w  . j  av  a  2 s .  co  m
        return (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(new ByteArrayInputStream(encodedDerCertificate));
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.ambientdynamix.web.WebUtils.java

/**
 * Returns the X509Certificate for the incoming packageName. Returns null if the packageName cannot be found (or if
 * there was a certificate exception).//from   w  w  w.j ava2 s .c o m
 */
public static X509Certificate getCertForApp(String packageName) {
    try {
        // Create packMgr, if needed
        if (packMgr == null) {
            packMgr = DynamixService.getAndroidContext().getPackageManager();
        }
        // Create certFactory, if needed
        if (certFactory == null) {
            certFactory = CertificateFactory.getInstance("X509");
        }
        PackageInfo packageInfo = packMgr.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
        Signature[] signatures = packageInfo.signatures;
        // signatures[0] is a DER encoded X.509 certificate
        byte[] cert = signatures[0].toByteArray();
        InputStream input = new ByteArrayInputStream(cert);
        X509Certificate c = (X509Certificate) certFactory.generateCertificate(input);
        return c;
    } catch (NameNotFoundException e) {
        Log.w(TAG, "Package not found for " + packageName + " - " + e);
    } catch (CertificateException e) {
        Log.w(TAG, "Certificate exception for " + packageName + " - " + e);
    }
    return null;
}

From source file:org.codice.ddf.security.sts.crl.CrlInterceptorTest.java

/**
 * Creates a mock message with a cert attached
 *
 * @param certificateString The string of the certificate to attach
 * @return A message object to be passed to the CrlInterceptor for testing
 * @throws CertificateException// w  w w  .jav  a 2  s  .com
 */
private Message createMockMessageWithCert(String certificateString) throws CertificateException {
    // create mock objects
    Message message = mock(Message.class);
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(message.get(AbstractHTTPDestination.HTTP_REQUEST)).thenReturn(request);

    // add in certificate
    InputStream stream = new ByteArrayInputStream(Base64.decodeBase64(certificateString.getBytes()));
    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) factory.generateCertificate(stream);
    X509Certificate[] certs = new X509Certificate[] { cert };
    when(request.getAttribute(("javax.servlet.request.X509Certificate"))).thenReturn(certs);

    return message;
}