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:net.sf.keystore_explorer.crypto.keystore.KeyStoreUtil.java

/**
 * Save a KeyStore to a file protected by a password.
 *
 * @param keyStore//from   w  ww  .j a  v a  2s.  com
 *            The KeyStore
 * @param keyStoreFile
 *            The file to save the KeyStore to
 * @param password
 *            The password to protect the KeyStore with
 * @throws CryptoException
 *             Problem encountered saving the KeyStore
 * @throws FileNotFoundException
 *             If the KeyStore file exists but is a directory rather than a
 *             regular file, does not exist but cannot be created, or cannot
 *             be opened for any other reason
 * @throws IOException
 *             An I/O error occurred
 */
public static void save(KeyStore keyStore, File keyStoreFile, Password password)
        throws CryptoException, IOException {
    KeyStoreType keyStoreType = KeyStoreType.resolveJce(keyStore.getType());

    if (!keyStoreType.isFileBased()) {
        throw new CryptoException(MessageFormat.format(res.getString("NoSaveKeyStoreNotFile.exception.message"),
                keyStoreType.jce()));
    }

    FileOutputStream fos = null;

    fos = new FileOutputStream(keyStoreFile);

    try {
        keyStore.store(fos, password.toCharArray());
    } catch (IOException ex) {
        throw new CryptoException(res.getString("NoSaveKeyStore.exception.message"), ex);
    } catch (KeyStoreException ex) {
        throw new CryptoException(res.getString("NoSaveKeyStore.exception.message"), ex);
    } catch (CertificateException ex) {
        throw new CryptoException(res.getString("NoSaveKeyStore.exception.message"), ex);
    } catch (NoSuchAlgorithmException ex) {
        throw new CryptoException(res.getString("NoSaveKeyStore.exception.message"), ex);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

From source file:net.sf.keystore_explorer.crypto.keystore.KeyStoreUtil.java

/**
 * Copy a KeyStore./*from  www.  j a  v a 2 s .co m*/
 *
 * @param keyStore
 *            KeyStore to copy
 * @return Copy
 * @throws CryptoException
 *             Problem encountered copying the KeyStore
 */
public static KeyStore copy(KeyStore keyStore) throws CryptoException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        char[] emptyPassword = {};

        keyStore.store(baos, emptyPassword);

        KeyStore theCopy = KeyStoreUtil.create(KeyStoreType.resolveJce(keyStore.getType()));
        theCopy.load(new ByteArrayInputStream(baos.toByteArray()), emptyPassword);

        return theCopy;
    } catch (CryptoException ex) {
        throw new CryptoException(res.getString("NoCopyKeyStore.exception.message"), ex);
    } catch (GeneralSecurityException ex) {
        throw new CryptoException(res.getString("NoCopyKeyStore.exception.message"), ex);
    } catch (IllegalStateException ex) {
        throw new CryptoException(res.getString("NoCopyKeyStore.exception.message"), ex);
    } catch (IOException ex) {
        throw new CryptoException(res.getString("NoCopyKeyStore.exception.message"), ex);
    }
}

From source file:com.springcryptoutils.core.keystore.DefaultKeyStoreFactoryBeanTest.java

@Test
public void testKeyStoreIsProperlyLoaded() {
    KeyStore keyStore = ctx.getBean(KeyStore.class);
    assertNotNull(keyStore);/*  w w w .jav  a2s  .  c o  m*/
    assertEquals("keyStoreType", "JKS", keyStore.getType());
}

From source file:com.springcryptoutils.core.keystore.KeyStoreMapperImplTest.java

@Test
public void testKeyStoreMapperIsProperlyConfigured() {
    assertNotNull(keyStoreMapper);//from   w  w  w . ja v a 2  s .co  m
    KeyStore keyStore1 = keyStoreMapper.getKeyStore("key1");
    KeyStore keyStore2 = keyStoreMapper.getKeyStore("key2");
    assertNotNull(keyStore1);
    assertNotNull(keyStore2);
    assertEquals("keyStoreType1", "JKS", keyStore1.getType());
    assertEquals("keyStoreType2", "JKS", keyStore2.getType());
    assertNotSame(keyStore1, keyStore2);
}

From source file:com.springcryptoutils.core.keystore.KeyStoreRegistryImplTest.java

@Test
public void testKeyStoreRegistryIsProperlyConfigured() {
    assertNotNull(keyStoreRegistry);/*from   w w  w. jav  a  2  s .  co  m*/
    KeyStore keystoreOne = keyStoreRegistry.get(new KeyStoreChooser() {
        public String getKeyStoreName() {
            return "keystoreOne";
        }
    });
    KeyStore keystoreTwo = keyStoreRegistry.get(new KeyStoreChooser() {
        public String getKeyStoreName() {
            return "keystoreTwo";
        }
    });
    assertNotNull(keystoreOne);
    assertNotNull(keystoreTwo);
    assertEquals("JKS", keystoreOne.getType());
    assertEquals("JKS", keystoreTwo.getType());
    assertNotSame(keystoreOne, keystoreTwo);
}

From source file:android.core.SSLSocketTest.java

/**
 * Regression test for 963650: javax.net.ssl.KeyManager has no implemented
 * (documented?) algorithms.//from  w  ww . ja va  2s .c  om
 */
public void testDefaultAlgorithms() throws Exception {
    SSLContext ctx = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
    KeyStore ks = KeyStore.getInstance("BKS");

    assertEquals("X509", kmf.getAlgorithm());
    assertEquals("X509", KeyManagerFactory.getDefaultAlgorithm());

    assertEquals("BKS", ks.getType());
    assertEquals("BKS", KeyStore.getDefaultType());
}

From source file:net.timewalker.ffmq4.listeners.tcp.io.TcpListener.java

private SSLContext createSSLContext() throws JMSException {
    try {// w  ww.j  a v a2  s . c om
        String sslProtocol = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_PROTOCOL, "SSLv3");
        String keyManagerAlgorithm = settings
                .getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYMANAGER_ALGORITHM, "SunX509");
        String keyStoreType = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYSTORE_TYPE,
                "JKS");
        String keyStorePath = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYSTORE_PATH,
                "../conf/server-keystore.jks");
        String keyStorePass = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYSTORE_PASWORD,
                "ffmqpass");
        String keyPass = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYSTORE_KEY_PASSWORD,
                "ffmqpass");

        SSLContext sslContext = SSLContext.getInstance(sslProtocol);
        log.debug("Created an SSL context : protocol=[" + sslContext.getProtocol() + "] provider=["
                + sslContext.getProvider() + "]");

        // Load available keys
        KeyManager[] keyManagers;
        File keyStoreFile = new File(keyStorePath);
        if (!keyStoreFile.canRead())
            throw new FFMQException("Cannot read keystore file : " + keyStoreFile.getAbsolutePath(),
                    "FS_ERROR");

        KeyStore ks = KeyStore.getInstance(keyStoreType);
        log.debug("Created keystore : type=[" + ks.getType() + "] provider=[" + ks.getProvider() + "]");
        char ksPass[] = keyStorePass.toCharArray();
        char ctPass[] = keyPass.toCharArray();
        log.debug("Loading keystore from " + keyStoreFile.getAbsolutePath());
        InputStream kis = new FileInputStream(keyStoreFile);
        ks.load(kis, ksPass);
        kis.close();

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
        log.debug("Created KeyManagerFactory : algorithm=[" + kmf.getAlgorithm() + "] provider=["
                + kmf.getProvider() + "]");
        log.debug("Initializing KeyManagerFactory with keystore ...");
        kmf.init(ks, ctPass);

        keyManagers = kmf.getKeyManagers();

        sslContext.init(keyManagers, null, null);

        return sslContext;
    } catch (JMSException e) {
        throw e;
    } catch (Exception e) {
        throw new FFMQException("Cannot create SSL context", "NETWORK_ERROR", e);
    }
}

From source file:org.apache.ws.security.components.crypto.CryptoBase.java

protected static String createKeyStoreErrorMessage(KeyStore keystore) throws KeyStoreException {
    Enumeration aliases = keystore.aliases();
    StringBuffer sb = new StringBuffer(keystore.size() * 7);
    boolean firstAlias = true;
    while (aliases.hasMoreElements()) {
        if (!firstAlias) {
            sb.append(", ");
        }/* ww  w  . j  ava2  s .  c o 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;
}

From source file:org.apache.ws.security.components.crypto.Merlin.java

private static 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(", ");
        }//from   w ww  .ja  v  a  2  s  .  com
        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;
}

From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java

@Deprecated //Remove this method as soon as upgrading from 5.0->6.x is dropped
private void processSoftKeystore(AuthenticationToken authenticationToken, File file, String softStorePassword,
        String softKeyPassword, boolean doNotStorePasswordsInMemory,
        List<InternalKeyBindingTrustEntry> trustDefaults) {
    KeyStore keyStore;
    final char[] passwordChars = softStorePassword.toCharArray();
    // Load keystore (JKS or PKCS#12)
    try {/*from   w  w  w  .j a v a 2 s  .  c  om*/
        keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(file), passwordChars);
    } catch (Exception e) {
        try {
            keyStore = KeyStore.getInstance("PKCS12", "BC");
            keyStore.load(new FileInputStream(file), passwordChars);
        } catch (Exception e2) {
            try {
                log.info("Unable to process " + file.getCanonicalPath() + " as a KeyStore.");
            } catch (IOException e3) {
                log.warn(e3.getMessage());
            }
            return;
        }
    }

    // Strip issuer certs, etc. and convert to PKCS#12
    try {
        keyStore = makeKeysOnlyP12(keyStore, passwordChars);
    } catch (Exception e) {
        throw new RuntimeException("failed to convert keystore to P12 during keybindings upgrade", e);
    }

    final String name = file.getName();
    if (cryptoTokenManagementSession.getIdFromName(name) != null) {
        return; // already upgraded
    }
    log.info(" Processing Soft KeyStore '" + name + "' of type " + keyStore.getType());
    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // Save the store using the same password as the keys are protected with (not the store password)
        // so we don't have to replace the protection for each key
        keyStore.store(baos, softKeyPassword.toCharArray());
        final Properties cryptoTokenProperties = new Properties();
        if (!doNotStorePasswordsInMemory) {
            log.info(" Auto-activation will be used.");
            BaseCryptoToken.setAutoActivatePin(cryptoTokenProperties, new String(softKeyPassword), true);
        } else {
            log.info(" Auto-activation will not be used.");
        }
        final int softCryptoTokenId = cryptoTokenManagementSession.createCryptoToken(authenticationToken, name,
                SoftCryptoToken.class.getName(), cryptoTokenProperties, baos.toByteArray(),
                softKeyPassword.toCharArray());
        createInternalKeyBindings(authenticationToken, softCryptoTokenId, keyStore, trustDefaults);
    } catch (Exception e) {
        log.warn(e.getMessage());
    }
}