Example usage for java.security KeyStore getCertificateChain

List of usage examples for java.security KeyStore getCertificateChain

Introduction

In this page you can find the example usage for java.security KeyStore getCertificateChain.

Prototype

public final Certificate[] getCertificateChain(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate chain associated with the given alias.

Usage

From source file:com.stargame.ad.util.http.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {// w w w.j  a  va 2 s  .  c  o m
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LogUtil.D) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                LogUtil.d(AuthSSLProtocolSocketFactory.class, " Certificate " + (c + 1) + ":");
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Subject DN: " + cert.getSubjectDN());
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Signature Algorithm: " + cert.getSigAlgName());
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Valid from: " + cert.getNotBefore());
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Valid until: " + cert.getNotAfter());
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LogUtil.D) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LogUtil.d(AuthSSLProtocolSocketFactory.class, "Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "  Subject DN: " + cert.getSubjectDN());
                        LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                "  Signature Algorithm: " + cert.getSigAlgName());
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "  Valid from: " + cert.getNotBefore());
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "  Valid until: " + cert.getNotAfter());
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:cn.org.eshow.framwork.http.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//w  w w.j a  v  a  2 s .co m
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (AbLogUtil.D) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        " Certificate " + (c + 1) + ":");
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Subject DN: " + cert.getSubjectDN());
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Signature Algorithm: " + cert.getSigAlgName());
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Valid from: " + cert.getNotBefore());
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Valid until: " + cert.getNotAfter());
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (AbLogUtil.D) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "  Subject DN: " + cert.getSubjectDN());
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                "  Signature Algorithm: " + cert.getSigAlgName());
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "  Valid from: " + cert.getNotBefore());
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "  Valid until: " + cert.getNotAfter());
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:org.kuali.coeus.propdev.impl.s2s.connect.S2SConnectorServiceBase.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig//from ww  w .j a v a2  s.c o m
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2sCommunicationException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2sCommunicationException {
    KeyStore keyStore = s2sCertificateReader.getKeyStore();
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        if (alias != null && mulitCampusEnabled) {
            KeyStore keyStoreAlias;
            keyStoreAlias = KeyStore.getInstance(s2sCertificateReader.getJksType());
            Certificate[] certificates = keyStore.getCertificateChain(alias);
            Key key = keyStore.getKey(alias, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(
                    alias, key, s2SConfigurationService
                            .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        } else {
            keyManagerFactory.init(keyStore, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        }
        KeyManager[] km = keyManagerFactory.getKeyManagers();
        tlsConfig.setKeyManagers(km);
        KeyStore trustStore = s2sCertificateReader.getTrustStore();
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();
        tlsConfig.setTrustManagers(tm);
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | CertificateException
            | IOException e) {
        LOG.error(e.getMessage(), e);
        throw new S2sCommunicationException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

From source file:org.sonatype.flexmojos.air.SignAirMojo.java

@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException, MojoFailureException {
    AIRPackager airPackager = new AIRPackager();
    try {//from w ww  .ja va2  s  .  c o m
        String c = this.classifier == null ? "" : "-" + this.classifier;
        File output = new File(project.getBuild().getDirectory(),
                project.getBuild().getFinalName() + c + "." + AIR);
        airPackager.setOutput(output);
        airPackager.setDescriptor(getAirDescriptor());

        KeyStore keyStore = KeyStore.getInstance(storetype);
        keyStore.load(new FileInputStream(keystore.getAbsolutePath()), storepass.toCharArray());
        String alias = keyStore.aliases().nextElement();
        airPackager.setPrivateKey((PrivateKey) keyStore.getKey(alias, storepass.toCharArray()));
        airPackager.setSignerCertificate(keyStore.getCertificate(alias));
        airPackager.setCertificateChain(keyStore.getCertificateChain(alias));
        if (this.timestampURL != null) {
            airPackager.setTimestampURL(TIMESTAMP_NONE.equals(this.timestampURL) ? null : this.timestampURL);
        }

        String packaging = project.getPackaging();
        if (AIR.equals(packaging)) {
            Set<Artifact> deps = project.getDependencyArtifacts();
            for (Artifact artifact : deps) {
                if (SWF.equals(artifact.getType())) {
                    File source = artifact.getFile();
                    String path = source.getName();
                    if (stripVersion && path.contains(artifact.getVersion())) {
                        path = path.replace("-" + artifact.getVersion(), "");
                    }
                    getLog().debug("  adding source " + source + " with path " + path);
                    airPackager.addSourceWithPath(source, path);
                }
            }
        } else if (SWF.equals(packaging)) {
            File source = project.getArtifact().getFile();
            String path = source.getName();
            getLog().debug("  adding source " + source + " with path " + path);
            airPackager.addSourceWithPath(source, path);
        } else {
            throw new MojoFailureException("Unexpected project packaging " + packaging);
        }

        if (includeFiles == null && includeFileSets == null) {
            includeFileSets = resources.toArray(new FileSet[0]);
        }

        if (includeFiles != null) {
            for (final String includePath : includeFiles) {
                String directory = project.getBuild().getOutputDirectory();
                addSourceWithPath(airPackager, directory, includePath);
            }
        }

        if (includeFileSets != null) {
            for (FileSet set : includeFileSets) {
                DirectoryScanner scanner = new DirectoryScanner();
                scanner.setBasedir(set.getDirectory());
                scanner.setIncludes((String[]) set.getIncludes().toArray(new String[0]));
                scanner.setExcludes((String[]) set.getExcludes().toArray(new String[0]));
                scanner.addDefaultExcludes();
                scanner.scan();

                String[] files = scanner.getIncludedFiles();
                for (String path : files) {
                    addSourceWithPath(airPackager, set.getDirectory(), path);
                }
            }
        }

        if (classifier != null) {
            projectHelper.attachArtifact(project, project.getArtifact().getType(), classifier, output);
        } else if (SWF.equals(packaging)) {
            projectHelper.attachArtifact(project, AIR, output);
        } else {
            project.getArtifact().setFile(output);
        }

        final List<Message> messages = new ArrayList<Message>();

        airPackager.setListener(new Listener() {
            public void message(final Message message) {
                messages.add(message);
            }

            public void progress(final int soFar, final int total) {
                getLog().info("  completed " + soFar + " of " + total);
            }
        });

        airPackager.createAIR();

        if (messages.size() > 0) {
            for (final Message message : messages) {
                getLog().error("  " + message.errorDescription);
            }

            throw new MojoExecutionException("Error creating AIR application");
        } else {
            getLog().info("  AIR package created: " + output.getAbsolutePath());
        }
    } catch (MojoExecutionException e) {
        // do not handle
        throw e;
    } catch (Exception e) {
        throw new MojoExecutionException("Error invoking AIR api", e);
    } finally {
        airPackager.close();
    }
}

From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java

private void copyNodeChain(KeyStore keyStore, String password, KeyStore newKeyStore, String newPassword) {
    try {//from w  w  w.j a  v  a  2 s . co  m
        // change the password to our local random one
        Key key = keyStore.getKey(nodeAlias, password.toCharArray());
        Certificate[] chain = keyStore.getCertificateChain(nodeAlias);
        X509Certificate[] x509Chain = new X509Certificate[chain.length];
        for (int i = 0; i < chain.length; i += 1) {
            x509Chain[i] = (X509Certificate) chain[i];
        }
        saveNodeCertificateChain(newKeyStore, key, newPassword, x509Chain[0], x509Chain);
    } catch (GeneralSecurityException e) {
        throw new CertificateException(e);
    }
}

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

/**
 * @throws java.lang.Exception/*from  ww w  .  ja  va  2 s.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:org.kuali.kra.s2s.service.impl.S2SConnectorServiceBase.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig//w  w w .ja  va  2 s.c  o m
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2SException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2SException {
    KeyStore keyStore = s2sCertificateReader.getKeyStore();
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        if (alias != null && mulitCampusEnabled) {
            KeyStore keyStoreAlias;
            keyStoreAlias = KeyStore.getInstance(s2sCertificateReader.getJksType());
            Certificate[] certificates = keyStore.getCertificateChain(alias);
            Key key = keyStore.getKey(alias,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(alias, key,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        } else {
            keyManagerFactory.init(keyStore,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        }
        KeyManager[] km = keyManagerFactory.getKeyManagers();
        tlsConfig.setKeyManagers(km);
        KeyStore trustStore = s2sCertificateReader.getTrustStore();
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();
        tlsConfig.setTrustManagers(tm);
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (UnrecoverableKeyException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (CertificateException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (IOException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

From source file:org.taverna.server.master.localworker.SecurityContextDelegateImpl.java

/**
 * Tests whether the given key-pair credential descriptor is valid. If it is
 * invalid, an exception will be thrown describing what the problem is.
 * // www .j a v  a2  s. co  m
 * @param keypairDescriptor
 *            The descriptor to validate.
 * @throws InvalidCredentialException
 *             If the descriptor is invalid
 * @throws KeyStoreException
 *             If we don't understand the keystore type or the contents of
 *             the keystore
 * @throws NoSuchAlgorithmException
 *             If the keystore is of a known type but we can't comprehend
 *             its security
 * @throws CertificateException
 *             If the keystore does not include enough information about the
 *             trust chain of the keypair
 * @throws UnrecoverableKeyException
 *             If we can't get the key out of the keystore
 * @throws IOException
 *             If we can't read the keystore for prosaic reasons (e.g., file
 *             absent)
 */
protected void validateKeyCredential(Credential.KeyPair keypairDescriptor)
        throws InvalidCredentialException, KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableKeyException {
    if (keypairDescriptor.credentialName == null || keypairDescriptor.credentialName.trim().isEmpty())
        throw new InvalidCredentialException("absent or empty credentialName");

    InputStream contentsAsStream;
    if (keypairDescriptor.credentialBytes != null && keypairDescriptor.credentialBytes.length > 0) {
        contentsAsStream = new ByteArrayInputStream(keypairDescriptor.credentialBytes);
        keypairDescriptor.credentialFile = null;
    } else if (keypairDescriptor.credentialFile == null || keypairDescriptor.credentialFile.trim().isEmpty())
        throw new InvalidCredentialException("absent or empty credentialFile");
    else {
        contentsAsStream = contents(keypairDescriptor.credentialFile);
        keypairDescriptor.credentialBytes = new byte[0];
    }
    if (keypairDescriptor.fileType == null || keypairDescriptor.fileType.trim().isEmpty())
        keypairDescriptor.fileType = KeyStore.getDefaultType();
    keypairDescriptor.fileType = keypairDescriptor.fileType.trim();

    KeyStore ks = KeyStore.getInstance(keypairDescriptor.fileType);
    char[] password = keypairDescriptor.unlockPassword.toCharArray();
    ks.load(contentsAsStream, password);

    try {
        keypairDescriptor.loadedKey = ks.getKey(keypairDescriptor.credentialName, password);
    } catch (UnrecoverableKeyException ignored) {
        keypairDescriptor.loadedKey = ks.getKey(keypairDescriptor.credentialName, new char[0]);
    }
    if (keypairDescriptor.loadedKey == null)
        throw new InvalidCredentialException("no such credential in key store");
    keypairDescriptor.loadedTrustChain = ks.getCertificateChain(keypairDescriptor.credentialName);
    if (keypairDescriptor.loadedTrustChain == null || keypairDescriptor.loadedTrustChain.length == 0)
        throw new InvalidCredentialException("could not establish trust chain for credential");
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data,
        String type, String fileName, String path, String storepass, KeyStore store)
        throws KeystoreEditorException {
    OutputStream fos = null;/*  w w  w  .ja v  a  2s . co m*/
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException("Alias cannot be null.");
        }
        Path storeFile = Paths.get(path);
        //check the two most common key/cert stores first (pkcs12 and jks)
        if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
            //priv key + cert chain
            KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
            pkcs12Store.load(inputStream, storePassword.toCharArray());
            Certificate[] chain = pkcs12Store.getCertificateChain(alias);
            Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
            if (key != null) {
                store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
            //java keystore file
            KeyStore jks = KeyStore.getInstance("jks");
            jks.load(inputStream, storePassword.toCharArray());
            Enumeration<String> aliases = jks.aliases();

            //we are going to store all entries from the jks regardless of the passed in alias
            while (aliases.hasMoreElements()) {
                String jksAlias = aliases.nextElement();

                if (jks.isKeyEntry(jksAlias)) {
                    Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
                    Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
                    store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
                } else {
                    Certificate certificate = jks.getCertificate(jksAlias);
                    store.setCertificateEntry(jksAlias, certificate);
                }
            }

            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //need to parse der separately from pem, der has the same mime type but is binary hence checking both
        } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
            ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
            ASN1Primitive asn1Primitive = asn1InputStream.readObject();
            X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            Certificate certificate = certificateFactory
                    .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
            if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                store.setCertificateEntry(cnStr, certificate);
            }
            store.setCertificateEntry(alias, certificate);
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //if it isn't one of the stores we support, it might be a key or cert by itself
        } else if (isPemParsable(type, fileName)) {
            //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            PEMParser pemParser = new PEMParser(reader);
            Object object;
            boolean setEntry = false;
            while ((object = pemParser.readObject()) != null) {
                if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
                    PEMKeyPair pemKeyPair;
                    if (object instanceof PEMEncryptedKeyPair) {
                        PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
                        JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
                        pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(
                                jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
                    } else {
                        pemKeyPair = (PEMKeyPair) object;
                    }

                    KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
                    PrivateKey privateKey = keyPair.getPrivate();
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
                    setEntry = true;
                } else if (object instanceof X509CertificateHolder) {
                    X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
                    Certificate certificate = certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
                    X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate)
                            .getSubject();
                    RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                    String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
                    if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                        store.setCertificateEntry(cnStr, certificate);
                    }
                    store.setCertificateEntry(alias, certificate);
                    setEntry = true;
                } else if (object instanceof ContentInfo) {
                    ContentInfo contentInfo = (ContentInfo) object;
                    if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
                        CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
                        OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
                        ASN1Set certificates = originatorInfo.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
                        SignedData signedData = SignedData.getInstance(contentInfo.getContent());
                        ASN1Set certificates = signedData.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    }
                } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    try {
                        store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
                        setEntry = true;
                    } catch (KeyStoreException keyEx) {
                        try {
                            PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(),
                                    keyPassword.toCharArray());
                            store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(),
                                    chain);
                            setEntry = true;
                        } catch (GeneralSecurityException e) {
                            LOGGER.error(
                                    "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.",
                                    e);
                            throw keyEx;
                        }
                    }
                }
            }
            if (setEntry) {
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Unable to add entry {} to store", alias, e);
        throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }
    init();
}

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

/**
 * @throws java.lang.Exception//from   w ww.  j  av  a2 s. 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

        }
    };
}