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:com.raspberry.library.util.AppUtils.java

/**
 * Judge whether an app is dubuggable/*from w  ww.j  av  a2  s  .c  o  m*/
 *
 * @param ctx
 * @return
 */
public static boolean isDebuggable(Context ctx) {
    boolean debuggable = false;
    try {
        PackageInfo pinfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(),
                PackageManager.GET_SIGNATURES);
        Signature signatures[] = pinfo.signatures;
        for (int i = 0; i < signatures.length; i++) {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            ByteArrayInputStream stream = new ByteArrayInputStream(signatures[i].toByteArray());
            X509Certificate cert = (X509Certificate) cf.generateCertificate(stream);
            debuggable = cert.getSubjectX500Principal().equals(DEBUG_DN);
            if (debuggable) {
                break;
            }
        }

    } catch (NameNotFoundException e) {
    } catch (CertificateException e) {
    }
    return debuggable;
}

From source file:learn.encryption.ssl.SSLContext_Https.java

/**
 * @description javaSSLContext//ww w  .  ja  v a2  s . c o  m
 * @description https?, SSLContext (NoHttp?SecureRandombug)
 * @description client.ks?server
 * @description ??
 * @description ????getSSLContext2()
 */
//@SuppressLint("TrulyRandom")
public static SSLContext getSSLContext() {
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLS");
        // ??, ??assets
        InputStream inputStream = new FileInputStream(new File("D:\\tomcatcert\\server.ks"));
        //App.getInstance().getAssets().open("srca.cer");

        // ??
        CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");

        // ?KeyStore
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(inputStream, "123456".toCharArray());
        //Certificate cer = cerFactory.generateCertificate(inputStream);
        Certificate cer = keyStore.getCertificate("clientKey");
        keyStore.setCertificateEntry("trust", cer);

        // KeyStorekeyManagerFactory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "123456".toCharArray());

        // KeyStoreTrustManagerFactory
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        // ?SSLContext
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sslContext;
}

From source file:org.codice.ddf.security.handler.pki.CrlCheckerTest.java

/**
 * Exctracts list of X509 certs from a given cert string
 *
 * @param certString Certificate string//w w  w . j av  a  2 s .co  m
 * @return List of X509 certs in the string
 */
private X509Certificate[] extractX509CertsFromString(String certString) throws CertificateException {
    InputStream stream = new ByteArrayInputStream(Base64.decodeBase64(certString.getBytes()));
    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) factory.generateCertificate(stream);
    X509Certificate[] certs = new X509Certificate[1];
    certs[0] = cert;

    return certs;
}

From source file:org.panbox.core.pairing.PAKCorePairingHandler.java

@Override
public void runOperation(Cipher cipher, SecretKeySpec spec) throws Exception {

    CertificateFactory certificateFactory = CertificateFactory.getInstance(KeyConstants.CERTIFICATE_ENCODING);

    String sendbase64;/*  w w  w. j a  v a  2 s  . co m*/

    switch (pairingType) {
    case MASTER:
        logger.debug("PAKCorePairingHandler : runOperation : Started to handle MASTER pairing");
        cipher.init(Cipher.ENCRYPT_MODE, spec);

        // master transmission
        logger.debug("PAKCorePairingHandler : runOperation : Will now send master/slave information...");

        sendbase64 = Base64.encodeBase64String(cipher.doFinal(
                PairingType.MASTER.toString().getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET))));
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64);

        // email, firstname, lastname, devicename transmission
        logger.debug("PAKCorePairingHandler : runOperation : Will now send personal information...");

        sendbase64 = Base64.encodeBase64String(
                cipher.doFinal(eMail.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET))));
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64);

        sendbase64 = Base64.encodeBase64String(
                cipher.doFinal(firstName.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET))));
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64);

        sendbase64 = Base64.encodeBase64String(
                cipher.doFinal(lastName.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET))));
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64);

        sendbase64 = Base64.encodeBase64String(
                cipher.doFinal(deviceName.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET))));
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64);

        // owner privatekeys + password
        logger.debug("PAKCorePairingHandler : runOperation : Will now send owner privatekeys...");

        sendbase64 = Base64.encodeBase64String(cipher.doFinal(Utils.toBytes(keyPassword)));
        Arrays.fill(keyPassword, '\u0000');
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64);

        sendbase64 = Base64.encodeBase64String(
                cipher.doFinal(new PKCS8EncodedKeySpec(ownerKeyEnc.getEncoded()).getEncoded()));
        // This code can be inserted once Java 8 implements destroy-Method
        // in order to remove key material securely from JVM memory
        // try {
        // Destroyable destroyEncKey = ownerKeyEnc;
        // destroyEncKey.destroy();
        // } catch (DestroyFailedException e1) {
        // logger.warn(
        // "PAKCorePairingHandler : runOperation : Could not destroy private enc key after pairing: ",
        // e1);
        // }
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64);

        sendbase64 = Base64.encodeBase64String(
                cipher.doFinal(new PKCS8EncodedKeySpec(ownerKeySign.getEncoded()).getEncoded()));
        // This code can be inserted once Java 8 implements destroy-Method
        // in order to remove key material securely from JVM memory
        // try {
        // Destroyable destroySignKey = ownerKeySign;
        // destroySignKey.destroy();
        // } catch (DestroyFailedException e1) {
        // logger.warn(
        // "PAKCorePairingHandler : runOperation : Could not destroy private sign key after pairing: ",
        // e1);
        // }
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64);

        logger.debug("PAKCorePairingHandler : runOperation : Will now send known devices...");

        sendbase64 = Base64.encodeBase64String(cipher.doFinal(Integer.toString(knownDevices.size())
                .getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET))));
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent numOfDevices: " + sendbase64);

        for (Map.Entry<String, X509Certificate> entry : knownDevices.entrySet()) {

            sendbase64 = Base64.encodeBase64String(
                    cipher.doFinal(entry.getKey().getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET))));
            dataOutputStream.writeObject(sendbase64);
            dataOutputStream.flush();
            logger.debug("PAKCorePairingHandler : runOperation : Sent devicename: " + sendbase64);

            sendbase64 = Base64.encodeBase64String(cipher.doFinal(entry.getValue().getEncoded()));
            dataOutputStream.writeObject(sendbase64);
            dataOutputStream.flush();
            logger.debug("PAKCorePairingHandler : runOperation : Sent devicecert: " + sendbase64);
        }

        logger.debug("PAKCorePairingHandler : runOperation : Will now send known contacts...");

        File vcardFile = File.createTempFile("panbox-pairing-temp", null);
        AbstractAddressbookManager.exportContacts(knownContacts, vcardFile);

        sendbase64 = Base64
                .encodeBase64String(cipher.doFinal(Files.readAllBytes(Paths.get(vcardFile.getAbsolutePath()))));
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent vcards: " + sendbase64);

        vcardFile.delete();

        // transmission of devicetype and devicekey

        cipher.init(Cipher.DECRYPT_MODE, spec);

        String base64encRecDevType = (String) dataInputStream.readObject();
        String base64encRecDevCert = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingHandler : runOperation : Received devType: " + base64encRecDevType);
        logger.debug("PAKCorePairingHandler : runOperation : Received devCert: " + base64encRecDevCert);

        devType = DeviceType.valueOf(new String(cipher.doFinal(Base64.decodeBase64(base64encRecDevType))));

        InputStream is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64encRecDevCert)));
        devCert = (X509Certificate) certificateFactory.generateCertificate(is);

        break;
    case SLAVE:
        logger.debug("PAKCorePairingHandler : runOperation : Started to handle SLAVE pairing");
        cipher.init(Cipher.ENCRYPT_MODE, spec);

        // slave transmission
        logger.debug("PAKCorePairingHandler : runOperation : Will now send master/slave information...");

        sendbase64 = Base64.encodeBase64String(cipher.doFinal(
                PairingType.SLAVE.toString().getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET))));
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64);

        // email, firstname, lastname, devicename transmission
        logger.debug("PAKCorePairingHandler : runOperation : Will now send personal information...");

        sendbase64 = Base64.encodeBase64String(
                cipher.doFinal(eMail.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET))));
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64);

        sendbase64 = Base64.encodeBase64String(
                cipher.doFinal(firstName.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET))));
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64);

        sendbase64 = Base64.encodeBase64String(
                cipher.doFinal(lastName.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET))));
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64);

        sendbase64 = Base64.encodeBase64String(
                cipher.doFinal(deviceName.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET))));
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64);

        // owner certs
        logger.debug("PAKCorePairingHandler : runOperation : Will now send owner certificates...");

        sendbase64 = Base64.encodeBase64String(cipher.doFinal(ownerCertEnc.getEncoded()));
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64);

        sendbase64 = Base64.encodeBase64String(cipher.doFinal(ownerCertSign.getEncoded()));
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64);

        logger.debug(
                "PAKCorePairingHandler : runOperation : Will now receive device information for device manager...");

        logger.debug("PAKCorePairingHandler : runOperation : Will now send known devices...");

        sendbase64 = Base64.encodeBase64String(cipher.doFinal(Integer.toString(knownDevices.size())
                .getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET))));
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent numOfDevices: " + sendbase64);

        for (Map.Entry<String, X509Certificate> entry : knownDevices.entrySet()) {

            sendbase64 = Base64.encodeBase64String(
                    cipher.doFinal(entry.getKey().getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET))));
            dataOutputStream.writeObject(sendbase64);
            dataOutputStream.flush();
            logger.debug("PAKCorePairingHandler : runOperation : Sent devicename: " + sendbase64);

            sendbase64 = Base64.encodeBase64String(cipher.doFinal(entry.getValue().getEncoded()));
            dataOutputStream.writeObject(sendbase64);
            dataOutputStream.flush();
            logger.debug("PAKCorePairingHandler : runOperation : Sent devicecert: " + sendbase64);
        }

        logger.debug("PAKCorePairingHandler : runOperation : Will now send known contacts...");

        vcardFile = File.createTempFile("panbox-pairing-temp", null);
        AbstractAddressbookManager.exportContacts(knownContacts, vcardFile);

        sendbase64 = Base64
                .encodeBase64String(cipher.doFinal(Files.readAllBytes(Paths.get(vcardFile.getAbsolutePath()))));
        dataOutputStream.writeObject(sendbase64);
        dataOutputStream.flush();
        logger.debug("PAKCorePairingHandler : runOperation : Sent vcards: " + sendbase64);

        vcardFile.delete();

        cipher.init(Cipher.DECRYPT_MODE, spec);

        // transmission of devicetype and devicekey
        base64encRecDevType = (String) dataInputStream.readObject();
        base64encRecDevCert = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingHandler : runOperation : Received devType: " + base64encRecDevType);
        logger.debug("PAKCorePairingHandler : runOperation : Received devCert: " + base64encRecDevCert);

        devType = DeviceType.valueOf(new String(cipher.doFinal(Base64.decodeBase64(base64encRecDevType))));

        is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64encRecDevCert)));
        devCert = (X509Certificate) certificateFactory.generateCertificate(is);
        break;
    default:
    }

    logger.debug("PAKCorePairingHandler : runOperation : Pairing finished. Will terminate session now.");

    closeConnection();
}

From source file:com.amazon.alexa.avs.companion.ProvisioningClient.java

private SSLSocketFactory getPinnedSSLSocketFactory(Context context) throws Exception {
    InputStream caCertInputStream = null;
    try {//from  ww  w .ja v a 2  s  . c o m
        caCertInputStream = context.getResources().openRawResource(R.raw.ca);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate caCert = cf.generateCertificate(caCertInputStream);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setCertificateEntry("myca", caCert);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
        return sslContext.getSocketFactory();
    } finally {
        IOUtils.closeQuietly(caCertInputStream);
    }
}

From source file:bobs.mcapisignature.CertUtils.java

public static X509Certificate getX509CertificateFromB64(String certBase64) throws CertificateException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf
            .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(certBase64)));

    return cert;//ww  w .java  2  s .c o  m
}

From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImplIT.java

/**
 * @throws java.lang.Exception/* ww w. ja  v  a 2  s . c  o m*/
 */
@BeforeClass
@Ignore
public static void setUpBeforeCLass() throws Exception {

    Security.addProvider(new BouncyCastleProvider());

    // Create some test username and passwords for services
    serviceURI = new URI("http://someservice");
    usernamePassword = new UsernamePassword("testuser", "testpasswd");
    serviceURI2 = new URI("http://someservice2");
    usernamePassword2 = new UsernamePassword("testuser2", "testpasswd2");
    serviceURI3 = new URI("http://someservice3");
    usernamePassword3 = new UsernamePassword("testuser3", "testpasswd3");

    // 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(trustedCertficateGoogleFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile);
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    trustedCertficateGoogle = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }
    // Load the test trusted certificate (belonging to heater.cs.man.ac.uk)
    File trustedCertFile2 = new File(trustedCertficateHeaterFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile2);
    trustedCertficateHeater = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }

    credentialManager = new CredentialManagerImpl();

    //      // The code below sets up the Keystore and Truststore files and loads some data into them
    //      // and saves them into a temp directory. These files can later be used for testing the Credential
    //      // Manager with non-empty keystores.
    //      Random randomGenerator = new Random();
    //      String credentialManagerDirectoryPath = System
    //            .getProperty("java.io.tmpdir")
    //            + System.getProperty("file.separator")
    //            + "taverna-security-"
    //            + randomGenerator.nextInt(1000000);
    //      System.out.println("Credential Manager's directory path: "
    //            + credentialManagerDirectoryPath);
    //      credentialManagerDirectory = new File(credentialManagerDirectoryPath);
    //      credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory);
    //      
    //      // Create the dummy master password provider
    //      masterPasswordProvider = new DummyMasterPasswordProvider();
    //      masterPasswordProvider.setMasterPassword(masterPassword);
    //      List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
    //      masterPasswordProviders.add(masterPasswordProvider);
    //      credentialManager.setMasterPasswordProviders(masterPasswordProviders);
    //      
    //      // Add some stuff into Credential Manager
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword, serviceURI);
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword2, serviceURI2);
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword3, serviceURI3);
    //      credentialManager.addKeyPair(privateKey, privateKeyCertChain);
    //      credentialManager.addTrustedCertificate(trustedCertficate);

    // Set up a random temp directory and copy the test keystore files 
    // from resources/security
    Random randomGenerator = new Random();
    String credentialManagerDirectoryPath = System.getProperty("java.io.tmpdir")
            + System.getProperty("file.separator") + "taverna-security-" + randomGenerator.nextInt(1000000);
    System.out.println("Credential Manager's directory path: " + credentialManagerDirectoryPath);
    credentialManagerDirectory = new File(credentialManagerDirectoryPath);
    if (!credentialManagerDirectory.exists()) {
        credentialManagerDirectory.mkdir();
    }
    URL keystoreFileURL = CredentialManagerImplIT.class.getResource("/security/t2keystore.ubr");
    File keystoreFile = new File(keystoreFileURL.getPath());
    File keystoreDestFile = new File(credentialManagerDirectory, "taverna-keystore.ubr");
    URL truststroreFileURL = CredentialManagerImplIT.class.getResource("/security/t2truststore.ubr");
    File truststoreFile = new File(truststroreFileURL.getPath());
    File truststoreDestFile = new File(credentialManagerDirectory, "taverna-truststore.ubr");
    FileUtils.copyFile(keystoreFile, keystoreDestFile);
    FileUtils.copyFile(truststoreFile, truststoreDestFile);
    credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory.toPath());

    // Create the dummy master password provider
    masterPasswordProvider = new DummyMasterPasswordProvider();
    masterPasswordProvider.setMasterPassword(masterPassword);
    List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
    masterPasswordProviders.add(masterPasswordProvider);
    credentialManager.setMasterPasswordProviders(masterPasswordProviders);

    // Set an empty list for trust confirmation providers
    credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>());

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

From source file:be.fedict.eid.dss.admin.portal.control.bean.RPBean.java

private static X509Certificate getCertificate(byte[] certificateBytes) throws CertificateException {

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
}

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  ww.  j  a  v  a2 s.c  o 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:IntergrationTest.OCSPIntegrationTest.java

/**
 * Read PEM certificate into javax.security.x509Certificate.
 *
 * @param pemCert//from w w w .  ja  va  2s .  c  o  m
 *
 * @return
 */
private X509Certificate readPemCert(byte[] pemCert) {
    CertificateFactory certificateFactory = null;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        e.printStackTrace();
    }
    X509Certificate x509cert;
    InputStream stream = new ByteArrayInputStream(pemCert);
    try {
        x509cert = (X509Certificate) certificateFactory.generateCertificate(stream);
        return x509cert;
    } catch (CertificateException e) {
        e.printStackTrace();
        return null;
    }
}