Example usage for java.security KeyStore setKeyEntry

List of usage examples for java.security KeyStore setKeyEntry

Introduction

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

Prototype

public final void setKeyEntry(String alias, Key key, char[] password, Certificate[] chain)
        throws KeyStoreException 

Source Link

Document

Assigns the given key to the given alias, protecting it with the given password.

Usage

From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java

@Override
public KeyStore initializeUser(UserInfo userInfo, String suppliedPassword) throws CertException {
    char[] password = suppliedPassword.toCharArray();
    KeyStore ks = null;
    String userName = userInfo.getUserFields().get(CNField.UserID);
    AliasWrapper keystoreAlias = new AliasWrapper(userName);
    try {//from w  w w .j a  va 2s.  c om
        ks = java.security.KeyStore.getInstance(KEYSTORE_TYPE);
        ks.load(null, password);
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyGen.initialize(KEY_SIZE);
        KeyPair keyPair = keyGen.genKeyPair();
        java.security.cert.Certificate[] chain = { getRootCertificate() };
        ks.setKeyEntry(keystoreAlias.getId(AliasType.KEY), keyPair.getPrivate(), password, chain);
        X509Certificate cert = getCertificate(keyPair, userInfo);
        ks.setCertificateEntry(keystoreAlias.getId(AliasType.CERT), cert);
    } catch (CertificateException e) {
        throw new CertException(e);
    } catch (IOException e) {
        throw new CertException(e);
    } catch (KeyStoreException e) {
        throw new CertException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertException(e);
    }
    return ks;
}

From source file:org.texai.x509.X509Utils.java

/** Initializes the installer keystore on the trusted development system, from where it is copied into the distributed code. */
public static synchronized void initializeInstallerKeyStore() {
    if (!X509Utils.isTrustedDevelopmentSystem()) {
        return;/*from  w  w w . jav a  2  s .co  m*/
    }
    String filePath = "data/installer-keystore.uber";
    File file = new File(filePath);
    if (file.exists()) {
        // do not overwrite it
        return;
    }
    try {
        LOGGER.info("creating the installer keystores");
        // the installer keystore consists of the single client X.509 certificate, which is generated and signed by
        // the Texai root certificate on the developement system that has the root private key.
        final KeyPair installerKeyPair = X509Utils.generateRSAKeyPair2048();
        final X509Certificate installerX509Certificate = X509Utils.generateX509Certificate(
                installerKeyPair.getPublic(), X509Utils.getRootPrivateKey(), X509Utils.getRootX509Certificate(),
                null);

        // proceed as though the JCE unlimited strength jurisdiction policy files are installed, which they will be on the
        // trusted development system.
        LOGGER.info("creating installer-keystore.uber");
        assert X509Utils.isJCEUnlimitedStrengthPolicy();
        KeyStore installerKeyStore = X509Utils.findOrCreateKeyStore(filePath, INSTALLER_KEYSTORE_PASSWORD);
        installerKeyStore.setKeyEntry(X509Utils.ENTRY_ALIAS, installerKeyPair.getPrivate(),
                INSTALLER_KEYSTORE_PASSWORD,
                new Certificate[] { installerX509Certificate, X509Utils.getRootX509Certificate() });
        installerKeyStore.store(new FileOutputStream(filePath), INSTALLER_KEYSTORE_PASSWORD);

        // then proceed after disabling the JCE unlimited strength jurisdiction policy files indicator
        X509Utils.setIsJCEUnlimitedStrengthPolicy(false);
        filePath = "data/installer-keystore.jceks";
        LOGGER.info("creating installer-keystore.jceks");
        installerKeyStore = X509Utils.findOrCreateKeyStore(filePath, INSTALLER_KEYSTORE_PASSWORD);
        installerKeyStore.setKeyEntry(X509Utils.ENTRY_ALIAS, installerKeyPair.getPrivate(),
                INSTALLER_KEYSTORE_PASSWORD,
                new Certificate[] { installerX509Certificate, X509Utils.getRootX509Certificate() });
        installerKeyStore.store(new FileOutputStream(filePath), INSTALLER_KEYSTORE_PASSWORD);
        // restore the JCE unlimited strength jurisdiction policy files indicator
        X509Utils.setIsJCEUnlimitedStrengthPolicy(true);
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException
            | SignatureException | InvalidKeyException | IOException | KeyStoreException
            | CertificateException ex) {
        LOGGER.error(StringUtils.getStackTraceAsString(ex));
        throw new TexaiException(ex);
    }

    //Postconditions
    assert !isTrustedDevelopmentSystem()
            || X509Utils.isJCEUnlimitedStrengthPolicy() : "JCE unlimited strength policy must be in effect";
}

From source file:org.texai.x509.X509Utils.java

/** Creates the Texai root X.509 certificate keystore on the trusted development system.  This
 * keystore also includes a jar-signing certificate.
 *///  ww  w . j a  va2  s.  co m
protected static synchronized void createTexaiRootKeyStore() {
    //Preconditions
    assert !isTrustedDevelopmentSystem() || X509Utils.isJCEUnlimitedStrengthPolicy();

    if (!isTrustedDevelopmentSystem()) {
        return;
    }
    final char[] keyStorePassword = getRootKeyStorePassword();
    assert keyStorePassword != null;
    final String filePath = System.getenv("SECURITY_DIR") + "/texai-keystore.jceks";
    final File serverKeyStoreFile = new File(filePath);
    if (serverKeyStoreFile.exists()) {
        // do not overwrite it
        return;
    }
    try {
        LOGGER.info("creating Texai root key pair");
        final KeyPair rootKeyPair = generateRSAKeyPair3072();
        LOGGER.info("creating Texai root X.509 certificate");
        final X509Certificate rootX509Certificate = generateRootX509Certificate(rootKeyPair);
        LOGGER.info("root certificate...\n" + rootX509Certificate);
        final StringBuilder stringBuilder = new StringBuilder();
        for (final byte b : rootX509Certificate.getEncoded()) {
            stringBuilder.append(Byte.toString(b));
            stringBuilder.append(", ");
        }
        LOGGER.info("root certificate...\n" + rootX509Certificate);
        LOGGER.info("\nroot certificate bytes...\n" + stringBuilder.toString());
        LOGGER.info("creating Texai root X.509 certificate keystore");
        final KeyStore rootKeyStore = X509Utils.findOrCreateJceksKeyStore(filePath, keyStorePassword);
        rootKeyStore.setKeyEntry(ROOT_ALIAS, rootKeyPair.getPrivate(), keyStorePassword,
                new Certificate[] { rootX509Certificate });

        // create and store the jar-signer certificate
        LOGGER.info("creating jar-signer key pair");
        final KeyPair jarSignerKeyPair = generateRSAKeyPair2048();
        LOGGER.info("creating jar-signer X.509 certificate");
        final UUID jarSignerUUID = UUID.randomUUID();
        LOGGER.info("jar-signer UUID: " + jarSignerUUID);
        final X509Certificate jarSignerX509Certificate = generateX509Certificate(jarSignerKeyPair.getPublic(),
                rootKeyPair.getPrivate(), rootX509Certificate, jarSignerUUID, "RootCertificate"); // domainComponent
        LOGGER.info("jar-signer certificate:\n" + jarSignerX509Certificate);
        rootKeyStore.setKeyEntry(JAR_SIGNER_ALIAS, jarSignerKeyPair.getPrivate(), keyStorePassword,
                new Certificate[] { jarSignerX509Certificate, rootX509Certificate });
        rootKeyStore.store(new FileOutputStream(filePath), keyStorePassword);

        //Postconditions
        final PrivateKey privateKey = (PrivateKey) rootKeyStore.getKey(ROOT_ALIAS, keyStorePassword);
        assert privateKey != null;

    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException
            | SignatureException | InvalidKeyException | IOException | KeyStoreException | CertificateException
            | UnrecoverableKeyException ex) {
        throw new TexaiException(ex);
    }
}

From source file:dk.itst.oiosaml.sp.configuration.ConfigurationHandler.java

public void handlePost(RequestContext context) throws ServletException, IOException {
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();

    if (!checkConfiguration(response))
        return;/*from w w w. j  a  v a 2s  .co m*/

    List<?> parameters = extractParameterList(request);

    String orgName = extractParameter("organisationName", parameters);
    String orgUrl = extractParameter("organisationUrl", parameters);
    String email = extractParameter("email", parameters);
    String entityId = extractParameter("entityId", parameters);
    final String password = extractParameter("keystorePassword", parameters);
    byte[] metadata = extractFile("metadata", parameters).get();
    FileItem ksData = extractFile("keystore", parameters);
    byte[] keystore = null;
    if (ksData != null) {
        keystore = ksData.get();
    }
    if (!checkNotNull(orgName, orgUrl, email, password, metadata, entityId) || metadata.length == 0
            || (keystore == null && !Boolean.valueOf(extractParameter("createkeystore", parameters)))) {
        Map<String, Object> params = getStandardParameters(request);
        params.put("error", "All fields must be filled.");
        params.put("organisationName", orgName);
        params.put("organisationUrl", orgUrl);
        params.put("email", email);
        params.put("keystorePassword", password);
        params.put("entityId", entityId);
        log.info("Parameters not correct: " + params);
        log.info("Metadata: " + new String(metadata));

        String res = renderTemplate("configure.vm", params, true);
        sendResponse(response, res);
        return;
    }

    Credential credential = context.getCredential();
    if (keystore != null && keystore.length > 0) {
        credential = CredentialRepository.createCredential(new ByteArrayInputStream(keystore), password);
    } else if (Boolean.valueOf(extractParameter("createkeystore", parameters))) {
        try {
            BasicX509Credential cred = new BasicX509Credential();
            KeyPair kp = dk.itst.oiosaml.security.SecurityHelper
                    .generateKeyPairFromURI("http://www.w3.org/2001/04/xmlenc#rsa-1_5", 1024);
            cred.setPrivateKey(kp.getPrivate());
            cred.setPublicKey(kp.getPublic());
            credential = cred;

            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(null, null);
            X509Certificate cert = dk.itst.oiosaml.security.SecurityHelper.generateCertificate(credential,
                    getEntityId(request));
            cred.setEntityCertificate(cert);

            ks.setKeyEntry("oiosaml", credential.getPrivateKey(), password.toCharArray(),
                    new Certificate[] { cert });
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ks.store(bos, password.toCharArray());

            keystore = bos.toByteArray();
            bos.close();
        } catch (Exception e) {
            log.error("Unable to generate credential", e);
            throw new RuntimeException("Unable to generate credential", e);
        }
    }

    EntityDescriptor descriptor = generateSPDescriptor(getBaseUrl(request), entityId, credential, orgName,
            orgUrl, email, Boolean.valueOf(extractParameter("enableArtifact", parameters)),
            Boolean.valueOf(extractParameter("enablePost", parameters)),
            Boolean.valueOf(extractParameter("enableSoap", parameters)),
            Boolean.valueOf(extractParameter("enablePostSLO", parameters)),
            Boolean.valueOf(extractParameter("supportOCESAttributeProfile", parameters)));
    File zipFile = generateZipFile(request.getContextPath(), password, metadata, keystore, descriptor);

    byte[] configurationContents = saveConfigurationInSession(request, zipFile);
    boolean written = writeConfiguration(getHome(servletContext), configurationContents);

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("home", getHome(servletContext));
    params.put("written", written);
    sendResponse(response, renderTemplate("done.vm", params, true));
}

From source file:org.signserver.server.cryptotokens.KeystoreCryptoTokenTest.java

/**
 * Test importing a new certificate chain to an existing keystore.
 * @throws Exception //w w  w .ja  v a  2  s. c  o  m
 */
public void testImportCertificateChain() throws Exception {
    LOG.info("testImportCertificateChain");

    final boolean autoActivate = false;

    final int workerId = WORKER_CMS;
    try {
        setCMSSignerPropertiesCombined(workerId, autoActivate);

        // Generate key and issue certificate
        final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
        kpg.initialize(1024);
        final KeyPair keyPair = kpg.generateKeyPair();

        // Create a key-pair and certificate in the keystore
        FileOutputStream out = null;
        try {
            KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
            ks.load(null, null);

            final X509Certificate[] chain = new X509Certificate[1];
            chain[0] = getSelfCertificate("CN=Test", (long) 30 * 24 * 60 * 60 * 365, keyPair);
            ks.setKeyEntry("newkey11", keyPair.getPrivate(), pin.toCharArray(), chain);

            out = new FileOutputStream(keystoreFile);
            ks.store(out, pin.toCharArray());
        } finally {
            IOUtils.closeQuietly(out);
        }

        workerSession.setWorkerProperty(workerId, "DEFAULTKEY", "newkey11");
        workerSession.reloadConfiguration(workerId);

        // Activate first so we can generate a key
        workerSession.activateSigner(workerId, pin);

        List<String> errors = workerSession.getStatus(workerId).getFatalErrors();
        assertTrue("Fatal errors: " + errors, workerSession.getStatus(workerId).getFatalErrors().isEmpty());

        // generate a new certificate
        final X509Certificate newCert = getSelfCertificate("CN=TestNew", (long) 30 * 24 * 60 * 60 * 365,
                keyPair);

        workerSession.importCertificateChain(workerId, Arrays.asList(newCert.getEncoded()), "newkey11", null);

        final Certificate readCert = workerSession.getSignerCertificate(workerId);
        assertTrue("Matching certificates", Arrays.equals(newCert.getEncoded(), readCert.getEncoded()));
    } finally {
        FileUtils.deleteQuietly(keystoreFile);
        removeWorker(workerId);
    }
}

From source file:org.jenkinsci.remoting.engine.HandlerLoopbackLoadStress.java

public HandlerLoopbackLoadStress(Config config)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        UnrecoverableKeyException, KeyManagementException, OperatorCreationException {
    this.config = config;
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048); // maximum supported by JVM with export restrictions
    keyPair = gen.generateKeyPair();//from w  w w  .j a  v  a 2  s.  c o  m

    Date now = new Date();
    Date firstDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(10));
    Date lastDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(-10));

    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo
            .getInstance(keyPair.getPublic().getEncoded());

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    X500Name subject = nameBuilder.addRDN(BCStyle.CN, getClass().getSimpleName()).addRDN(BCStyle.C, "US")
            .build();

    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(subject, BigInteger.ONE, firstDate,
            lastDate, subject, subjectPublicKeyInfo);

    JcaX509ExtensionUtils instance = new JcaX509ExtensionUtils();

    certGen.addExtension(X509Extension.subjectKeyIdentifier, false,
            instance.createSubjectKeyIdentifier(subjectPublicKeyInfo));

    ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE_PROVIDER)
            .build(keyPair.getPrivate());

    certificate = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE_PROVIDER)
            .getCertificate(certGen.build(signer));

    char[] password = "password".toCharArray();

    KeyStore store = KeyStore.getInstance("jks");
    store.load(null, password);
    store.setKeyEntry("alias", keyPair.getPrivate(), password, new Certificate[] { certificate });

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(store, password);

    context = SSLContext.getInstance("TLS");
    context.init(kmf.getKeyManagers(), new TrustManager[] { new BlindTrustX509ExtendedTrustManager() }, null);

    mainHub = IOHub.create(executorService);
    // on windows there is a bug whereby you cannot mix ServerSockets and Sockets on the same selector
    acceptorHub = File.pathSeparatorChar == 59 ? IOHub.create(executorService) : mainHub;
    legacyHub = new NioChannelHub(executorService);
    executorService.submit(legacyHub);
    serverSocketChannel = ServerSocketChannel.open();

    JnlpProtocolHandler handler = null;
    for (JnlpProtocolHandler h : new JnlpProtocolHandlerFactory(executorService).withNioChannelHub(legacyHub)
            .withIOHub(mainHub).withSSLContext(context).withPreferNonBlockingIO(!config.bio)
            .withClientDatabase(new JnlpClientDatabase() {
                @Override
                public boolean exists(String clientName) {
                    return true;
                }

                @Override
                public String getSecretOf(@Nonnull String clientName) {
                    return secretFor(clientName);
                }
            }).withSSLClientAuthRequired(false).handlers()) {
        if (config.name.equals(h.getName())) {
            handler = h;
            break;
        }
    }
    if (handler == null) {
        throw new RuntimeException("Unknown handler: " + config.name);
    }
    this.handler = handler;

    acceptor = new Acceptor(serverSocketChannel);
    runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    _getProcessCpuTime = _getProcessCpuTime(operatingSystemMXBean);
    garbageCollectorMXBeans = new ArrayList<GarbageCollectorMXBean>(
            ManagementFactory.getGarbageCollectorMXBeans());
    Collections.sort(garbageCollectorMXBeans, new Comparator<GarbageCollectorMXBean>() {
        @Override
        public int compare(GarbageCollectorMXBean o1, GarbageCollectorMXBean o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    stats = new Stats();
}

From source file:org.signserver.server.cryptotokens.PKCS11CryptoToken.java

@Override
public void importCertificateChain(final List<Certificate> certChain, final String alias,
        final char[] athenticationCode, final Map<String, Object> params, final IServices services)
        throws CryptoTokenOfflineException {
    try {/* w w w .j  a  v  a2s  . c o  m*/
        final KeyStore keyStore = delegate.getActivatedKeyStore();
        final Key key = keyStore.getKey(alias, athenticationCode);

        CryptoTokenHelper.ensureNewPublicKeyMatchesOld(keyStore, alias, certChain.get(0));

        keyStore.setKeyEntry(alias, key, athenticationCode, certChain.toArray(new Certificate[0]));
    } catch (KeyStoreException ex) {
        LOG.error(ex, ex);
        throw new CryptoTokenOfflineException(ex);
    } catch (NoSuchAlgorithmException ex) {
        LOG.error(ex, ex);
        throw new CryptoTokenOfflineException(ex);
    } catch (UnrecoverableKeyException ex) {
        LOG.error(ex, ex);
        throw new CryptoTokenOfflineException(ex);
    }
}

From source file:be.solidx.hot.nio.http.SSLContextBuilder.java

private KeyManagerFactory handleClientKeyCertURLProvided(Map<String, Object> options)
        throws SSLContextInitializationException {

    InputStream keyInputStream = null;
    InputStream certInputStream = null;

    try {//from  w  w w. j a  v  a  2 s .c  o  m
        KeyManagerFactory keyManagerFactory = null;
        KeyStore keyStore = KeyStore.getInstance(JKS);
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

        byte[] key = IOUtils.toByteArray(getInputStream(new URI(options.get(KEY).toString())));
        Certificate certCertificate = certificateFactory
                .generateCertificate(getInputStream(new URI(options.get(CERT).toString())));
        char[] password = options.get(PASSPHRASE).toString().toCharArray();

        keyStore.load(null, null);
        // No CA needed, just add pivate key and associated public key to a keystore
        keyStore.setKeyEntry(KEY, SSLUtils.toPrivateKey(new ByteArrayInputStream(key)), password,
                new Certificate[] { certCertificate });

        keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        keyManagerFactory.init(keyStore, password);

        return keyManagerFactory;
    } catch (NullPointerException | UnrecoverableKeyException | KeyStoreException | CertificateException
            | NoSuchAlgorithmException | IOException | URISyntaxException | InvalidKeySpecException e) {
        throw new SSLContextInitializationException(e);
    } finally {
        if (keyInputStream != null) {
            try {
                keyInputStream.close();
            } catch (IOException e) {
            }
        }
        if (certInputStream != null) {
            try {
                certInputStream.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.X509SecurityHandler.java

@InterfaceAudience.Private
@VisibleForTesting//from www  .j a v  a2s.  c  om
protected KeyStoresWrapper createApplicationStores(CertificateBundle certificateBundle, PrivateKey privateKey,
        String appUser, ApplicationId appId) throws GeneralSecurityException, IOException {
    char[] password = generateRandomPassword();

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);
    X509Certificate[] chain = new X509Certificate[2];
    chain[0] = certificateBundle.certificate;
    chain[1] = certificateBundle.issuer;
    keyStore.setKeyEntry(appUser, privateKey, password, chain);

    KeyStore systemTrustStore = loadSystemTrustStore(config);
    KeyStore appTrustStore = KeyStore.getInstance("JKS");
    appTrustStore.load(null, null);

    Enumeration<String> aliases = systemTrustStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        X509Certificate cert = (X509Certificate) systemTrustStore.getCertificate(alias);
        appTrustStore.setCertificateEntry(alias, cert);
    }

    return new KeyStoresWrapper(keyStore, password, appTrustStore, password, appUser, appId);
}

From source file:org.renci.ahab.ndllib.transport.OrcaSMXMLRPCProxy.java

private KeyStore loadX509Data(FileInputStream certIS, FileInputStream keyIS, String keyAlias,
        String keyPassword) throws Exception {

    if (Security.getProvider("BC") == null) {
        Security.addProvider(new BouncyCastleProvider());
    }/*  w  w w .  jav a  2  s .co  m*/

    /*
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
                    if (Security.getProvider("BC") == null) {
                            Security.addProvider(new BouncyCastleProvider());
                    }
                    System.out.println("Currently loaded security providers:");
                    for (Provider p: Security.getProviders()) {
                            System.out.println("Provider " + p + " - " +  p.getName());
                    }
                    System.out.println("End of security provider list.");
                    return null;
            }
    });
    */

    JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter().setProvider("BC");
    JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter().setProvider("BC");

    Object object;

    PEMParser pemParser = new PEMParser(new BufferedReader(new InputStreamReader(keyIS, "UTF-8")));

    PrivateKey privKey = null;

    while ((object = pemParser.readObject()) != null) {
        if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
            InputDecryptorProvider decProv = new JceOpenSSLPKCS8DecryptorProviderBuilder()
                    .build(keyPassword.toCharArray());
            privKey = keyConverter
                    .getPrivateKey(((PKCS8EncryptedPrivateKeyInfo) object).decryptPrivateKeyInfo(decProv));
            break;
        } else if (object instanceof PEMEncryptedKeyPair) {
            PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder()
                    .build(keyPassword.toCharArray());
            privKey = keyConverter.getPrivateKey(
                    (((PEMEncryptedKeyPair) object).decryptKeyPair(decProv)).getPrivateKeyInfo());
            break;
        } else if (object instanceof PEMKeyPair) {
            privKey = keyConverter.getPrivateKey(((PEMKeyPair) object).getPrivateKeyInfo());
            break;
        }
    }

    if (privKey == null)
        throw new Exception("Private key file did not contain a private key.");

    pemParser = new PEMParser(new BufferedReader(new InputStreamReader(certIS, "UTF-8")));

    ArrayList<Certificate> certs = new ArrayList<Certificate>();

    while ((object = pemParser.readObject()) != null) {
        if (object instanceof X509CertificateHolder) {
            certs.add(certConverter.getCertificate((X509CertificateHolder) object));
        }
    }

    if (certs.isEmpty())
        throw new Exception("Certificate file contained no certificates.");

    KeyStore ks = KeyStore.getInstance("jks");
    ks.load(null);
    ks.setKeyEntry(keyAlias, privKey, keyPassword.toCharArray(), certs.toArray(new Certificate[certs.size()]));

    return ks;
}