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.kse.gui.actions.ImportCaReplyFromFileAction.java

/**
 * Do action./*ww w . j  ava  2s .c o m*/
 */
@Override
protected void doAction() {
    try {
        KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
        KeyStoreState currentState = history.getCurrentState();

        String alias = kseFrame.getSelectedEntryAlias();

        Password password = getEntryPassword(alias, currentState);

        if (password == null) {
            return;
        }

        KeyStoreState newState = currentState.createBasisForNextState(this);

        KeyStore keyStore = newState.getKeyStore();
        KeyStoreType keyStoreType = KeyStoreType.resolveJce(keyStore.getType());

        Key privateKey = keyStore.getKey(alias, password.toCharArray());

        File caReplyFile = chooseCaFile();
        if (caReplyFile == null) {
            return;
        }

        X509Certificate[] certs = openCaReply(caReplyFile);

        if ((certs == null) || (certs.length == 0)) {
            return;
        }

        certs = X509CertUtil.orderX509CertChain(certs);

        X509Certificate[] exitingEntryCerts = X509CertUtil
                .orderX509CertChain(X509CertUtil.convertCertificates(keyStore.getCertificateChain(alias)));

        if (!exitingEntryCerts[0].getPublicKey().equals(certs[0].getPublicKey())) {
            JOptionPane.showMessageDialog(frame,
                    res.getString("ImportCaReplyFromFileAction.NoMatchPubKeyCaReply.message"),
                    res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"),
                    JOptionPane.WARNING_MESSAGE);
            return;
        }

        // Holds the new certificate chain for the entry should the import succeed
        X509Certificate[] newCertChain = null;

        if (!applicationSettings.getEnableImportCaReplyTrustCheck()) {
            newCertChain = certs;
        } else {
            KeyStore caCertificates = getCaCertificates();
            KeyStore windowsTrustedRootCertificates = getWindowsTrustedRootCertificates();

            // PKCS #7 reply - try and match the self-signed root with any
            // of the certificates in the CA Certificates or current KeyStore
            if (certs.length > 1) {
                X509Certificate rootCert = certs[certs.length - 1];
                String matchAlias = null;

                if (caCertificates != null) // Match against CA Certificates KeyStore
                {
                    matchAlias = X509CertUtil.matchCertificate(caCertificates, rootCert);
                }

                // Match against Windows Trusted Root Certificates KeyStore
                if ((windowsTrustedRootCertificates != null) && (matchAlias == null)) {
                    matchAlias = X509CertUtil.matchCertificate(windowsTrustedRootCertificates, rootCert);
                }

                if (matchAlias == null) // Match against current KeyStore
                {
                    matchAlias = X509CertUtil.matchCertificate(keyStore, rootCert);
                }

                if (matchAlias == null) {
                    // No match for the root certificate - display the certificate to the user for confirmation
                    JOptionPane.showMessageDialog(frame,
                            res.getString("ImportCaReplyFromFileAction.NoMatchRootCertCaReplyConfirm.message"),
                            res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"),
                            JOptionPane.INFORMATION_MESSAGE);

                    DViewCertificate dViewCertificate = new DViewCertificate(frame,
                            MessageFormat.format(
                                    res.getString("ImportCaReplyFromFileAction.CertDetailsFile.Title"),
                                    caReplyFile.getName()),
                            new X509Certificate[] { rootCert }, null, DViewCertificate.NONE);
                    dViewCertificate.setLocationRelativeTo(frame);
                    dViewCertificate.setVisible(true);

                    int selected = JOptionPane.showConfirmDialog(frame,
                            res.getString("ImportCaReplyFromFileAction.AcceptCaReply.message"),
                            res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"),
                            JOptionPane.YES_NO_OPTION);
                    if (selected != JOptionPane.YES_OPTION) {
                        return;
                    }

                    newCertChain = certs;
                } else {
                    newCertChain = certs;
                }
            }
            // Single X.509 certificate reply - try and establish a chain of
            // trust from the certificate and ending with a root CA self-signed certificate
            else {
                // Establish trust against current KeyStore
                ArrayList<KeyStore> compKeyStores = new ArrayList<>();
                compKeyStores.add(keyStore);

                if (caCertificates != null) {
                    // Establish trust against CA Certificates KeyStore
                    compKeyStores.add(caCertificates);
                }

                if (windowsTrustedRootCertificates != null) {
                    // Establish trust against Windows Trusted Root Certificates KeyStore
                    compKeyStores.add(windowsTrustedRootCertificates);
                }

                X509Certificate[] trustChain = X509CertUtil.establishTrust(certs[0],
                        compKeyStores.toArray(new KeyStore[compKeyStores.size()]));

                if (trustChain != null) {
                    newCertChain = trustChain;
                } else {
                    // Cannot establish trust for the certificate - fail
                    JOptionPane.showMessageDialog(frame,
                            res.getString("ImportCaReplyFromFileAction.NoTrustCaReply.message"),
                            res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"),
                            JOptionPane.WARNING_MESSAGE);
                    return;
                }
            }
        }

        if (keyStoreType.isFileBased()) {
            // TODO: why or when is delete actually necessary???
            keyStore.deleteEntry(alias);
            keyStore.setKeyEntry(alias, privateKey, password.toCharArray(), newCertChain);
        } else {
            keyStore.setKeyEntry(alias, privateKey, password.toCharArray(), newCertChain);
        }

        currentState.append(newState);

        kseFrame.updateControls(true);

        JOptionPane.showMessageDialog(frame,
                res.getString("ImportCaReplyFromFileAction.ImportCaReplySuccessful.message"),
                res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"),
                JOptionPane.INFORMATION_MESSAGE);
    } catch (Exception ex) {
        DError.displayError(frame, ex);
    }
}

From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#createCertificateRequest(List, String, int, int)
 *//*from   ww w .  j  a  v  a2  s  . co  m*/
public synchronized File createCertificateRequest(final List<String> subjectData, final String storePassword,
        final int validityPeriod, final int keySize) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", subjectData);
        DEBUGGER.debug("Value: {}", validityPeriod);
        DEBUGGER.debug("Value: {}", keySize);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final String signatureAlgorithm = certConfig.getSignatureAlgorithm();
    final String certificateAlgorithm = certConfig.getCertificateAlgorithm();
    final File privateKeyDirectory = FileUtils
            .getFile(certConfig.getPrivateKeyDirectory() + "/" + subjectData.get(0));
    final File publicKeyDirectory = FileUtils
            .getFile(certConfig.getPublicKeyDirectory() + "/" + subjectData.get(0));
    final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + subjectData.get(0));
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + subjectData.get(0));
    final X500Name x500Name = new X500Name("CN=" + subjectData.get(0) + ",OU=" + subjectData.get(1) + ",O="
            + subjectData.get(2) + ",L=" + subjectData.get(3) + ",ST=" + subjectData.get(4) + ",C="
            + subjectData.get(5) + ",E=" + subjectData.get(6));

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("signatureAlgorithm: {}", signatureAlgorithm);
        DEBUGGER.debug("certificateAlgorithm: {}", certificateAlgorithm);
        DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory);
        DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory);
        DEBUGGER.debug("csrDirectory: {}", csrDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("x500Name: {}", x500Name);
    }

    File csrFile = null;
    JcaPEMWriter csrPemWriter = null;
    JcaPEMWriter publicKeyWriter = null;
    JcaPEMWriter privateKeyWriter = null;
    FileOutputStream csrFileStream = null;
    FileOutputStream keyStoreStream = null;
    FileOutputStream publicKeyFileStream = null;
    FileOutputStream privateKeyFileStream = null;
    OutputStreamWriter csrFileStreamWriter = null;
    OutputStreamWriter privateKeyStreamWriter = null;
    OutputStreamWriter publicKeyStreamWriter = null;

    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, storePassword.toCharArray());

        if (DEBUG) {
            DEBUGGER.debug("KeyStore: {}", keyStore);
        }

        SecureRandom random = new SecureRandom();
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(certificateAlgorithm);
        keyGenerator.initialize(keySize, random);

        if (DEBUG) {
            DEBUGGER.debug("KeyGenerator: {}", keyGenerator);
        }

        KeyPair keyPair = keyGenerator.generateKeyPair();

        if (DEBUG) {
            DEBUGGER.debug("KeyPair: {}", keyPair);
        }

        if (keyPair != null) {
            final Signature sig = Signature.getInstance(signatureAlgorithm);
            final PrivateKey privateKey = keyPair.getPrivate();
            final PublicKey publicKey = keyPair.getPublic();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
                DEBUGGER.debug("PrivateKey: {}", privateKey);
                DEBUGGER.debug("PublicKey: {}", publicKey);
            }

            sig.initSign(privateKey, random);
            ContentSigner signGen = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey);

            if (DEBUG) {
                DEBUGGER.debug("ContentSigner: {}", signGen);
            }

            Calendar expiry = Calendar.getInstance();
            expiry.add(Calendar.DAY_OF_YEAR, validityPeriod);

            if (DEBUG) {
                DEBUGGER.debug("Calendar: {}", expiry);
            }

            CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

            if (DEBUG) {
                DEBUGGER.debug("CertificateFactory: {}", certFactory);
            }

            X509Certificate[] issuerCert = new X509Certificate[] { (X509Certificate) certFactory
                    .generateCertificate(new FileInputStream(certConfig.getIntermediateCertificateFile())) };

            if (DEBUG) {
                DEBUGGER.debug("X509Certificate[]: {}", (Object) issuerCert);
            }

            keyStore.setCertificateEntry(certConfig.getRootCertificateName(), certFactory.generateCertificate(
                    new FileInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()))));
            keyStore.setCertificateEntry(certConfig.getIntermediateCertificateName(),
                    certFactory.generateCertificate(new FileInputStream(
                            FileUtils.getFile(certConfig.getIntermediateCertificateFile()))));

            PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name,
                    publicKey);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequestBuilder: {}", builder);
            }

            PKCS10CertificationRequest csr = builder.build(signGen);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequest: {}", csr);
            }

            // write private key
            File privateKeyFile = FileUtils.getFile(privateKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFile: {}", privateKeyFile);
            }

            if (!(privateKeyFile.createNewFile())) {
                throw new IOException("Failed to store private file");
            }

            privateKeyFileStream = new FileOutputStream(privateKeyFile);
            privateKeyStreamWriter = new OutputStreamWriter(privateKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFileStream: {}", privateKeyFileStream);
                DEBUGGER.debug("privateKeyStreamWriter: {}", privateKeyStreamWriter);
            }

            privateKeyWriter = new JcaPEMWriter(privateKeyStreamWriter);
            privateKeyWriter.writeObject(privateKey);
            privateKeyWriter.flush();
            privateKeyStreamWriter.flush();
            privateKeyFileStream.flush();

            // write public key
            File publicKeyFile = FileUtils.getFile(publicKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PUBLICKEY_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFile: {}", publicKeyFile);
            }

            if (!(publicKeyFile.createNewFile())) {
                throw new IOException("Failed to store public key file");
            }

            publicKeyFileStream = new FileOutputStream(publicKeyFile);
            publicKeyStreamWriter = new OutputStreamWriter(publicKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            publicKeyWriter = new JcaPEMWriter(publicKeyStreamWriter);
            publicKeyWriter.writeObject(publicKey);
            publicKeyWriter.flush();
            publicKeyStreamWriter.flush();
            publicKeyFileStream.flush();

            // write csr
            csrFile = FileUtils
                    .getFile(csrDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.CSR_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("csrFile: {}", csrFile);
            }

            if (!(csrFile.createNewFile())) {
                throw new IOException("Failed to store CSR file");
            }

            csrFileStream = new FileOutputStream(csrFile);
            csrFileStreamWriter = new OutputStreamWriter(csrFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            csrPemWriter = new JcaPEMWriter(csrFileStreamWriter);
            csrPemWriter.writeObject(csr);
            csrPemWriter.flush();
            csrFileStreamWriter.flush();
            csrFileStream.flush();

            File keyStoreFile = FileUtils
                    .getFile(storeDirectory + "/" + subjectData.get(0) + "." + KeyStore.getDefaultType());

            if (DEBUG) {
                DEBUGGER.debug("keyStoreFile: {}", keyStoreFile);
            }

            keyStoreStream = FileUtils.openOutputStream(keyStoreFile);

            if (DEBUG) {
                DEBUGGER.debug("keyStoreStream: {}", keyStoreStream);
            }

            keyStore.setKeyEntry(subjectData.get(0), (Key) keyPair.getPrivate(), storePassword.toCharArray(),
                    issuerCert);
            keyStore.store(keyStoreStream, storePassword.toCharArray());
            keyStoreStream.flush();

            if (DEBUG) {
                DEBUGGER.debug("KeyStore: {}", keyStore);
            }
        } else {
            throw new CertificateManagementException("Failed to generate keypair. Cannot continue.");
        }
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (InvalidKeyException ikx) {
        throw new CertificateManagementException(ikx.getMessage(), ikx);
    } catch (OperatorCreationException ocx) {
        throw new CertificateManagementException(ocx.getMessage(), ocx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } finally {
        if (csrFileStreamWriter != null) {
            IOUtils.closeQuietly(csrFileStreamWriter);
        }

        if (csrFileStream != null) {
            IOUtils.closeQuietly(csrFileStream);
        }

        if (csrPemWriter != null) {
            IOUtils.closeQuietly(csrPemWriter);
        }

        if (publicKeyFileStream != null) {
            IOUtils.closeQuietly(publicKeyFileStream);
        }

        if (publicKeyStreamWriter != null) {
            IOUtils.closeQuietly(publicKeyStreamWriter);
        }

        if (publicKeyWriter != null) {
            IOUtils.closeQuietly(publicKeyWriter);
        }

        if (privateKeyFileStream != null) {
            IOUtils.closeQuietly(privateKeyFileStream);
        }

        if (privateKeyStreamWriter != null) {
            IOUtils.closeQuietly(privateKeyStreamWriter);
        }

        if (privateKeyWriter != null) {
            IOUtils.closeQuietly(privateKeyWriter);
        }

        if (keyStoreStream != null) {
            IOUtils.closeQuietly(keyStoreStream);
        }
    }

    return csrFile;
}