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.texai.x509.X509Utils.java

/** Adds an entry to the specified keystore, creating the keystore if it does not already exist.
 *
 * @param keyStoreFilePath the file path to the keystore
 * @param keyStorePassword the keystore's password
 * @param alias the entry alias//from   w w w . j  av  a2 s .  c  o  m
 * @param certPath the certificate path to add
 * @param privateKey the private key associated with the first certificate in the path
 * @return the keystore
 * @throws KeyStoreException
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws NoSuchProviderException
 */
public static KeyStore addEntryToKeyStore(final String keyStoreFilePath, final char[] keyStorePassword,
        final String alias, final CertPath certPath, final PrivateKey privateKey) throws KeyStoreException,
        IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException {
    //Preconditions
    assert keyStoreFilePath != null : "keyStoreFilePath must not be null";
    assert !keyStoreFilePath.isEmpty() : "keyStoreFilePath must not be empty";
    assert keyStorePassword != null : "keyStorePassword must not be null";
    assert alias != null : "alias must not be null";
    assert !alias.isEmpty() : "alias must not be empty";

    final KeyStore keyStore = X509Utils.findOrCreateKeyStore(keyStoreFilePath, keyStorePassword);
    final Certificate[] certificateChain = new Certificate[certPath.getCertificates().size() + 1];
    for (int i = 0; i < certPath.getCertificates().size(); i++) {
        certificateChain[i] = certPath.getCertificates().get(i);
    }
    certificateChain[certPath.getCertificates().size()] = X509Utils.getRootX509Certificate();
    keyStore.setKeyEntry(alias, privateKey, keyStorePassword, certificateChain);
    keyStore.store(new FileOutputStream(keyStoreFilePath), keyStorePassword);

    //Postconditions
    assert keyStore != null : "keyStore must not be null";

    return keyStore;
}

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

/**
 * Tests that a worker just set up with a key store containing a new
 * key-pair and is activated manually gets status ACTIVE.
 * @throws Exception/*from ww w.  jav  a2s.  c o m*/
 */
public void testActivateWithNewKeystore() throws Exception {
    LOG.info("testActivateWithNewKeystore");

    final boolean autoActivate = false;

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

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

            // Generate key and issue certificate
            final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
            kpg.initialize(1024);
            final KeyPair keyPair = kpg.generateKeyPair();
            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = getSelfCertificate("CN=TestActivateWithNewKeystore" + ", C=SE",
                    (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());

    } finally {
        FileUtils.deleteQuietly(keystoreFile);
        removeWorker(workerId);
    }
}

From source file:org.eclipse.gyrex.admin.ui.http.jetty.internal.ImportCertificateDialog.java

void importKeystore(final InputStream in) throws Exception {
    KeyStore tempKs;//from  w ww  . jav a  2 s  . com
    if (keystoreTypeField.isSelected(0)) {
        tempKs = KeyStore.getInstance("JKS");
    } else if (keystoreTypeField.isSelected(1)) {
        tempKs = KeyStore.getInstance("PKCS12");
    } else {
        throw new IllegalArgumentException(
                "Please select a keystore type before uploading a keystore and retry.");
    }

    final String keystorePassword = keyStorePasswordField.getText();
    final String keyPassword = keyPasswordField.getText();

    // load keystore
    tempKs.load(new BufferedInputStream(in), null != keystorePassword ? keystorePassword.toCharArray() : null);

    // initialize new JKS store
    final KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null);

    generatedKeystorePassword = UUID.randomUUID().toString().toCharArray();
    generatedKeyPassword = UUID.randomUUID().toString().toCharArray();

    // verify and copy into new store
    final Enumeration aliases = tempKs.aliases();
    while (aliases.hasMoreElements()) {
        final String alias = (String) aliases.nextElement();
        if (tempKs.isKeyEntry(alias)) {
            final Key key = tempKs.getKey(alias, null != keyPassword ? keyPassword.toCharArray()
                    : null != keystorePassword ? keystorePassword.toCharArray() : null);
            Certificate[] chain = tempKs.getCertificateChain(alias);
            if (null == chain) {
                final Certificate certificate = tempKs.getCertificate(alias);
                if (null == certificate) {
                    // skip to next
                    continue;
                }
                chain = new Certificate[] { certificate };
            }
            ks.setKeyEntry("jetty", key, generatedKeyPassword, chain);
            break;
        }
    }

    if (!ks.aliases().hasMoreElements()) {
        throw new IllegalArgumentException(
                "The uploaded keystore does not have a valid key + certificate chain entry. Please use a different keystore and retry.");
    }

    // write into bytes
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    ks.store(out, generatedKeystorePassword);

    keystoreBytes = out.toByteArray();
}

From source file:org.metaeffekt.dcc.commons.ant.CreateKeystoreTask.java

private void createKeyStore(File file, char[] password) throws GeneralSecurityException, IOException {
    final KeyStore keyStore = KeyUtils.loadKeyStore(file, getKeystoreType(), password);

    for (KeyEntry keyEntry : getKeysEntries()) {
        PrivateKey key = KeyUtils.loadKey(keyEntry.getKeyFile());
        List<Certificate> certificates = new ArrayList<Certificate>();
        for (CertificateEntry certEntry : keyEntry.getCertificateFiles()) {
            Certificate certificate = KeyUtils.loadCertificate(certEntry.getCertificateFile());
            certificates.add(certificate);

            final String chain = certEntry.getChain();
            if (!StringUtils.isBlank(chain)) {
                String chainWithCommaSeparator = chain.replace(";", ",");

                String[] splitChain = chainWithCommaSeparator.split(",");

                for (String chainCertFile : splitChain) {
                    if (!StringUtils.isBlank(chainCertFile)) {
                        chainCertFile = chainCertFile.trim();

                        Certificate chainCertificate = KeyUtils
                                .loadCertificate(certEntry.getChainBaseDir() + "/" + chainCertFile);

                        certificates.add(chainCertificate);
                    }/*from w  ww  .ja v a  2 s . co m*/
                }
            }

        }

        char[] passwd = password;
        if (keyEntry.getPassword() != null) {
            passwd = keyEntry.getPassword().toCharArray();
        }

        keyStore.setKeyEntry(keyEntry.getAlias(), key, passwd,
                certificates.toArray(new Certificate[certificates.size()]));
    }

    KeyUtils.persistKeyStore(keyStore, file, password);
}

From source file:org.apache.stratos.keystore.mgt.KeyStoreGenerator.java

/**
 * This method generates the keypair and stores it in the keystore
 *
 * @param keyStore A keystore instance//from  www .  j av  a  2 s .co m
 * @return Generated public key for the tenant
 * @throws KeyStoreMgtException Error when generating key pair
 */
private X509Certificate generateKeyPair(KeyStore keyStore) throws KeyStoreMgtException {
    try {
        CryptoUtil.getDefaultCryptoUtil();
        //generate key pair
        KeyPairGenerator keyPairGenerator = null;
        keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // Common Name and alias for the generated certificate
        String commonName = "CN=" + tenantDomain + ", OU=None, O=None L=None, C=None";

        //generate certificates
        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
        v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()));
        v3CertGen.setIssuerDN(new X509Principal(commonName));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        v3CertGen.setSubjectDN(new X509Principal(commonName));
        v3CertGen.setPublicKey(keyPair.getPublic());
        v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");
        X509Certificate PKCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());

        //add private key to KS
        keyStore.setKeyEntry(tenantDomain, keyPair.getPrivate(), password.toCharArray(),
                new java.security.cert.Certificate[] { PKCertificate });
        return PKCertificate;
    } catch (Exception ex) {
        String msg = "Error while generating the certificate for tenant :" + tenantDomain + ".";
        log.error(msg, ex);
        throw new KeyStoreMgtException(msg, ex);
    }

}

From source file:org.oscarehr.sharingcenter.actions.SecurityInfrastructureServlet.java

private String importCertificates(Integer infrastructureId, InputStream inputStream) {

    String status = "fail";
    OscarProperties oscarProperties = OscarProperties.getInstance();
    String keyStoreFile = oscarProperties.getProperty("TOMCAT_KEYSTORE_FILE");
    String trustStoreFile = oscarProperties.getProperty("TOMCAT_TRUSTSTORE_FILE");
    String keyStorePass = oscarProperties.getProperty("TOMCAT_KEYSTORE_PASSWORD");
    String trustStorePass = oscarProperties.getProperty("TOMCAT_TRUSTSTORE_PASSWORD");

    InfrastructureDao dao = SpringUtils.getBean(InfrastructureDao.class);
    InfrastructureDataObject infrastructure = dao.getInfrastructure(infrastructureId);

    String alias = infrastructure.getAlias();
    PrivateKey privateKey = null;
    KeyStore ks = null;
    KeyStore ts = null;/*from  w w w  .  j  av  a  2 s.  c o m*/

    try {
        //acquiring the private key
        Base64 base64 = new Base64();
        byte[] privKey = base64.decode(infrastructure.getBase64EncodedPrivateKey());
        privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privKey));

        ks = SslUtility.loadKeyStore(keyStoreFile, keyStorePass.toCharArray());
        ts = SslUtility.loadKeyStore(trustStoreFile, trustStorePass.toCharArray());

    } catch (SslException ex) {
        LOGGER.info(ex);
    } catch (InvalidKeySpecException ex) {
        LOGGER.info(ex);
    } catch (NoSuchAlgorithmException ex) {
        LOGGER.info(ex);
    }

    if (ks != null && ts != null && privateKey != null) {
        // import certificates to keystore and truststore
        try {
            // extract certificates
            ArrayList<X509Certificate> certificates = SslUtility.extractX509Certificates(inputStream);
            // get the private key and add certificate chain
            X509Certificate[] chain = new X509Certificate[2];
            ks.setKeyEntry(alias, privateKey, keyStorePass.toCharArray(), certificates.toArray(chain));

            // save the keystore
            ks.store(new FileOutputStream(keyStoreFile), keyStorePass.toCharArray());

            // add root CA certificate truststore
            ArrayList<X509Certificate> caCerts = SslUtility.retrieveCACertificates(certificates);
            for (X509Certificate x509Certificate : caCerts) {
                ts.setCertificateEntry(alias, x509Certificate);
            }

            // save the truststore
            ts.store(new FileOutputStream(trustStoreFile), trustStorePass.toCharArray());
            status = "import";
        } catch (NoSuchAlgorithmException ex) {
            LOGGER.info(ex);
        } catch (CertificateException ex) {
            LOGGER.info(ex);
        } catch (KeyStoreException ex) {
            LOGGER.info(ex);
        } catch (IOException ex) {
            LOGGER.info(ex);
        } catch (SslException ex) {
            LOGGER.info(ex);
        }
    } else {
        LOGGER.debug("Bad data. Keystore/Truststore/PrivateKey might be null");
    }

    return status;

}

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 .  j  a  v  a2  s  .  com*/
    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:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

public KeyStore addKeyPair(KeyStore keyStore, String keyStorePassphrase, KeyPair keyPair, String keyPairName,
        String keyPairPassphrase, String keyPairSubjectDN) throws CryptoException {
    logger.debug("Adding key pair to existing key store");

    try {/*  w ww .  j ava 2s .  c  om*/
        // Create the public key certificate for storage in the key store.
        X509Certificate cert = generateV3Certificate(keyPair, keyPairSubjectDN);
        X500PrivateCredential privateCredentials = new X500PrivateCredential(cert, keyPair.getPrivate(),
                keyPairName);

        Certificate[] certChain = new X509Certificate[1];
        certChain[0] = privateCredentials.getCertificate();

        // Load our generated key store up. They all have the same password, which we set.
        keyStore.load(null, keyStorePassphrase.toCharArray());

        /* Add certificate which contains the public key and set the private key as a key entry in the key store */
        keyStore.setCertificateEntry(privateCredentials.getAlias(), privateCredentials.getCertificate());
        keyStore.setKeyEntry(privateCredentials.getAlias(), keyPair.getPrivate(),
                keyPairPassphrase.toCharArray(), certChain);

        return keyStore;
    } catch (NoSuchAlgorithmException e) {
        this.logger.error("NoSuchAlgorithmException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (CertificateException e) {
        this.logger.error("CertificateException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (KeyStoreException e) {
        this.logger.error("KeyStoreException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (IOException e) {
        this.logger.error("IOException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    }
}

From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java

void importPrivateKey(String keyAlias, String keyPassword, InputStream fl, InputStream certstream)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException,
        KeyStoreException {/*from   www  . ja  v  a2  s  . c  o m*/
    KeyInfoManager keyInfoManager = null;

    writeLock.lock();
    try {
        keyInfoManager = getKeyInfoManager(getKeyMetaDataFileLocation());
        KeyStore ks = loadKeyStore(getKeyStoreParameters(), keyInfoManager);

        // loading Key
        byte[] keyBytes = new byte[fl.available()];
        KeyFactory kf = KeyFactory.getInstance("RSA");
        fl.read(keyBytes, 0, fl.available());
        fl.close();
        PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyBytes);
        PrivateKey key = kf.generatePrivate(keysp);

        // loading CertificateChain
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        @SuppressWarnings("rawtypes")
        Collection c = cf.generateCertificates(certstream);
        Certificate[] certs = new Certificate[c.toArray().length];

        certs = (Certificate[]) c.toArray(new Certificate[0]);

        // storing keystore
        ks.setKeyEntry(keyAlias, key, keyPassword.toCharArray(), certs);

        if (logger.isDebugEnabled()) {
            logger.debug("Key and certificate stored.");
            logger.debug("Alias:" + keyAlias);
        }

        ks.store(new FileOutputStream(getKeyStoreParameters().getLocation()), keyPassword.toCharArray());
    } finally {
        if (keyInfoManager != null) {
            keyInfoManager.clear();
        }

        writeLock.unlock();
    }
}

From source file:org.dataone.proto.trove.net.SocketFactoryManager.java

/**
 * Load PEM file contents into in-memory keystore NOTE: this implementation uses Bouncy Castle security provider
 *
 * @return the keystore that will provide the material
 * @throws KeyStoreException//from www. j  a v  a 2  s  .  c  o m
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 */
private KeyStore getKeyStore()
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {

    // if the location has been set, use it
    KeyStore keyStore = null;
    Object pemObject = null;

    keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, keyStorePassword.toCharArray());

    // get the private key and certificate from the PEM
    // TODO: find a way to do this with default Java provider (not Bouncy Castle)?
    Security.addProvider(new BouncyCastleProvider());
    PEMParser pemReader = new PEMParser(new FileReader(clientCertificateLocation));

    X509Certificate certificate = null;
    PrivateKey privateKey = null;
    KeyPair keyPair = null;

    while ((pemObject = pemReader.readObject()) != null) {
        if (pemObject instanceof PrivateKey) {
            privateKey = (PrivateKey) pemObject;
        } else if (pemObject instanceof KeyPair) {
            keyPair = (KeyPair) pemObject;
            privateKey = keyPair.getPrivate();
        } else if (pemObject instanceof X509Certificate) {
            certificate = (X509Certificate) pemObject;
        }
    }
    if (certificate == null) {
        log.warn("Certificate is null");
    } else {
        if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253)
                .equals(certificate.getIssuerX500Principal().getName(X500Principal.RFC2253))) {
            log.warn("Certificate is Self Signed");
        }
    }
    Certificate[] chain = new Certificate[] { certificate };

    // set the entry
    keyStore.setKeyEntry("cilogon", privateKey, keyStorePassword.toCharArray(), chain);

    return keyStore;

}