Example usage for java.security KeyStore getType

List of usage examples for java.security KeyStore getType

Introduction

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

Prototype

public final String getType() 

Source Link

Document

Returns the type of this keystore.

Usage

From source file:org.kse.gui.actions.ImportCaReplyFromFileAction.java

/**
 * Do action.//  w w 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:org.lockss.util.TestKeyStoreUtil.java

public void testDefaults() throws Exception {
    Properties p = initProps();// w  w w . j ava  2 s.co  m
    KeyStore ks = KeyStoreUtil.createKeyStore(p);
    List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases()));
    assertIsomorphic(SetUtil.set("mykey", "mycert"), SetUtil.theSet(aliases));
    assertNotNull(ks.getCertificate("mycert"));
    assertNull(ks.getCertificate("foocert"));
    assertEquals("JCEKS", ks.getType());
}

From source file:org.lockss.util.TestKeyStoreUtil.java

public void testStoreJks() throws Exception {
    File dir = getTempDir();//from ww  w  . j av  a 2  s  .c  o  m
    File file = new File(dir, "test.ks");
    Properties p = initProps();
    p.put(KeyStoreUtil.PROP_KEYSTORE_FILE, file.toString());
    p.put(KeyStoreUtil.PROP_KEYSTORE_TYPE, "JKS");
    p.put(KeyStoreUtil.PROP_KEYSTORE_PROVIDER, "");
    assertFalse(file.exists());
    KeyStore ks = KeyStoreUtil.createKeyStore(p);
    assertTrue(file.exists());

    KeyStore ks2 = loadKeyStore(ks.getType(), file, PASSWD);
    List aliases = ListUtil.fromIterator(new EnumerationIterator(ks2.aliases()));
    assertIsomorphic(SetUtil.set("mykey", "mycert"), SetUtil.theSet(aliases));
    assertNotNull(ks2.getCertificate("mycert"));
    assertNull(ks2.getCertificate("foocert"));
    assertEquals("JKS", ks2.getType());
}

From source file:org.lockss.util.TestKeyStoreUtil.java

public void testStore() throws Exception {
    File dir = getTempDir();//from   w w  w . j  av a  2s.  c o  m
    File file = new File(dir, "test.ks");
    Properties p = initProps();
    p.put(KeyStoreUtil.PROP_KEYSTORE_FILE, file.toString());
    assertFalse(file.exists());
    KeyStore ks = KeyStoreUtil.createKeyStore(p);
    assertTrue(file.exists());

    KeyStore ks2 = loadKeyStore(ks.getType(), file, PASSWD);
    List aliases = ListUtil.fromIterator(new EnumerationIterator(ks2.aliases()));
    assertIsomorphic(SetUtil.set("mykey", "mycert"), SetUtil.theSet(aliases));
    assertNotNull(ks2.getCertificate("mycert"));
    assertNull(ks2.getCertificate("foocert"));
    assertEquals("JCEKS", ks2.getType());
}

From source file:org.obm.sync.push.client.SSLContextFactoryTest.java

@Test
public void testKeyStoreIsPKCS12() throws Exception {
    InputStream pkcs12Stream = ClassLoader.getSystemClassLoader().getResourceAsStream("pkcs_pwd_toto.p12");
    char[] pkcs12Password = "toto".toCharArray();

    KeyStore keyStore = SSLContextFactory.loadPKCS12KeyStore(pkcs12Stream, pkcs12Password);

    InputStream pkcs12InnerX509 = ClassLoader.getSystemClassLoader().getResourceAsStream("pkcs_inner_x509.crt");
    Certificate pkcs12InnerCertificate = CertificateFactory.getInstance("x509")
            .generateCertificate(pkcs12InnerX509);
    assertThat(keyStore.getType()).isEqualToIgnoringCase("pkcs12");
    assertThat(keyStore.getCertificate("client2")).isEqualTo(pkcs12InnerCertificate);
}

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

/** Finds or creates the keystore specified by the given path.
 *
 * @param filePath the file path to the keystore
 * @param password the keystore password
 * @return the keystore//w ww . j a v  a2 s .c  om
 * @throws KeyStoreException if no Provider supports a KeyStoreSpi implementation for the specified type
 * @throws IOException if there is an I/O or format problem with the keystore data,
 * if a password is required but not given, or if the given password was incorrect
 * @throws NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found
 * @throws CertificateException if any of the certificates in the keystore could not be loaded
 * @throws NoSuchProviderException if the cryptography provider cannot be found
 */
public static KeyStore findOrCreateKeyStore(final String filePath, final char[] password)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        NoSuchProviderException {
    //Preconditions
    assert filePath != null : "filePath must not be null";
    if (isJCEUnlimitedStrengthPolicy()) {
        assert filePath.endsWith(".uber") : "file extension must be .uber";
    } else {
        assert filePath.endsWith(".jceks") : "file extension must be .jceks";
    }
    assert password != null : "password must not be null";
    assert password.length > 0 : "password must not be empty";

    final File keyStoreFile = new File(filePath);
    KeyStore keyStore;
    if (isJCEUnlimitedStrengthPolicy()) {
        keyStore = KeyStore.getInstance("UBER", BOUNCY_CASTLE_PROVIDER);
    } else {
        keyStore = KeyStore.getInstance("JCEKS");
    }
    if (keyStoreFile.exists()) {
        try (final FileInputStream keyStoreInputStream = new FileInputStream(keyStoreFile)) {
            keyStore.load(keyStoreInputStream, password);
        }
    } else {
        keyStore.load(null, null);
        try (final FileOutputStream keyStoreOutputStream = new FileOutputStream(keyStoreFile)) {
            keyStore.store(keyStoreOutputStream, password);
        }
    }

    //Postconditions
    assert !filePath.endsWith(".uber") || keyStore.getType().equals("UBER") : "keyStore type is "
            + keyStore.getType() + ", expected UBER, filePath: " + filePath;

    return keyStore;
}

From source file:org.wisdom.engine.ssl.SSLServerContext.java

private KeyManagerFactory getKeyManagerFactoryFromKeyStore(final File maybeRoot, final String path)
        throws KeyStoreException {
    KeyManagerFactory kmf;//from  www .j av a  2 s  .co m
    File file = new File(path);
    if (!file.isFile()) {
        // Second chance.
        file = new File(maybeRoot, path);
    }

    LOGGER.info("\t key store: " + file.getAbsolutePath());
    final KeyStore keyStore = KeyStore
            .getInstance(accessor.getConfiguration().getWithDefault("https.keyStoreType", "JKS"));
    LOGGER.info("\t key store type: " + keyStore.getType());
    LOGGER.info("\t key store provider: " + keyStore.getProvider());
    final char[] password = accessor.getConfiguration().getWithDefault("https.keyStorePassword", "")
            .toCharArray();
    LOGGER.info("\t key store password length: " + password.length);
    final String algorithm = accessor.getConfiguration().getWithDefault("https.keyStoreAlgorithm",
            KeyManagerFactory.getDefaultAlgorithm());
    LOGGER.info("\t key store algorithm: " + algorithm);
    if (file.isFile()) {
        FileInputStream stream = null;
        try {
            stream = new FileInputStream(file);
            keyStore.load(stream, password);
            kmf = KeyManagerFactory.getInstance(algorithm);
            kmf.init(keyStore, password);
        } catch (final Exception e) {
            throw new RuntimeException(HTTPSFAIL + e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    } else {
        throw new RuntimeException(
                "Cannot load key store from '" + file.getAbsolutePath() + "', " + "the file does not exist");
    }
    return kmf;
}

From source file:org.wisdom.engine.ssl.SSLServerContext.java

private TrustManagerFactory getTrustManagerFactoryFromKeyStore(final File maybeRoot, final String path)
        throws KeyStoreException {
    final TrustManagerFactory tmf;
    File file = new File(path);
    if (!file.isFile()) {
        // Second chance.
        file = new File(maybeRoot, path);
    }/*from   www. j a va 2  s.  com*/

    LOGGER.info("\t trust store: " + file.getAbsolutePath());
    final KeyStore trustStore = KeyStore
            .getInstance(accessor.getConfiguration().getWithDefault("https.trustStoreType", "JKS"));
    LOGGER.info("\t trust store type: " + trustStore.getType());
    LOGGER.info("\t trust store provider: " + trustStore.getProvider());
    final char[] password = accessor.getConfiguration().getWithDefault("https.trustStorePassword", "")
            .toCharArray();
    LOGGER.info("\t trust store password length: " + password.length);
    final String algorithm = accessor.getConfiguration().getWithDefault("https.trustStoreAlgorithm",
            KeyManagerFactory.getDefaultAlgorithm());
    LOGGER.info("\t trust store algorithm: " + algorithm);
    if (file.isFile()) {
        FileInputStream stream = null;
        try {
            stream = new FileInputStream(file);
            trustStore.load(stream, password);
            tmf = TrustManagerFactory.getInstance(algorithm);
            tmf.init(trustStore);
        } catch (final Exception e) {
            throw new RuntimeException(HTTPSFAIL + e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    } else {
        throw new RuntimeException(
                "Cannot load trust store from '" + file.getAbsolutePath() + "', " + "the file does not exist");
    }
    return tmf;
}

From source file:org.wso2.carbon.webapp.ext.cxf.crypto.CXFServerCrypto.java

private String createKeyStoreErrorMessage(KeyStore keystore) throws KeyStoreException {
    Enumeration<String> aliases = keystore.aliases();
    StringBuilder sb = new StringBuilder(keystore.size() * 7);
    boolean firstAlias = true;
    while (aliases.hasMoreElements()) {
        if (!firstAlias) {
            sb.append(", ");
        }/*w w w .  ja v a  2  s  . co m*/
        sb.append(aliases.nextElement());
        firstAlias = false;
    }
    String msg = " in keystore of type [" + keystore.getType() + "] from provider [" + keystore.getProvider()
            + "] with size [" + keystore.size() + "] and aliases: {" + sb.toString() + "}";
    return msg;
}