Example usage for java.security KeyStore size

List of usage examples for java.security KeyStore size

Introduction

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

Prototype

public final int size() throws KeyStoreException 

Source Link

Document

Retrieves the number of entries in this keystore.

Usage

From source file:com.emc.cto.ridagent.rid.util.HTTPSender.java

public static Map<String, Object> httpSend(PipelineOutput output, String destURL) {

    /* Set up TLS mutual authentication */

    KeyStore keystore = null;
    try {//from w ww.  j  a v  a  2 s . c  o  m
        keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    InputStream keystoreInput = null;
    try {
        keystoreInput = new FileInputStream(m_keystorePath);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        keystore.load(keystoreInput, m_keystorePassword.toCharArray());
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Keystore has " + keystore.size() + " keys");
        }
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    KeyStore truststore = null;
    try {
        truststore = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    InputStream truststoreInput = null;
    try {
        truststoreInput = new FileInputStream(m_truststorePath);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        truststore.load(truststoreInput, m_truststorePassword.toCharArray());
    } catch (NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (CertificateException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Truststore has " + truststore.size() + " keys");
        }
    } catch (KeyStoreException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    SSLSocketFactory schemeSocketFactory = null;

    try {
        schemeSocketFactory = new SSLSocketFactory(keystore, m_keystorePassword, truststore);
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    schemeRegistry.register(new Scheme(m_protocol, m_port, schemeSocketFactory));
    final HttpParams httpParams = new BasicHttpParams();
    DefaultHttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(schemeRegistry),
            httpParams);

    /* Prepare the request to send */

    String body = null;
    Map<String, Object> responseMap = new HashMap<String, Object>();
    List<com.emc.documentum.xml.xproc.io.Source> sources = output.getSources(output.getPrimaryOutputPort());

    if (sources != null && !sources.isEmpty()) {
        // pipeline should only return a single value - we return the first as the output
        Node node = sources.get(0).getNode();
        InputStream is = sources.get(0).getInputStream();
        Reader rdr = sources.get(0).getReader();

        //For now we implement node only since we assume content is in the node
        if (node != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Node has content");
            }
            body = Utilities.nodeToString(node);

        } else if (is != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Input stream has content");
            }

        } else if (rdr != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Reader has content");
            }
        }
    }

    HttpEntity request = new StringEntity(body, ContentType.TEXT_XML);

    //Create POST method
    HttpPost postMethod = new HttpPost(destURL);
    postMethod.setHeader("User-Agent", "EMC RID System");
    postMethod.setHeader("Content-Type", "text/xml");
    postMethod.setEntity(request);

    /* POST the request and process the response */
    HttpResponse httpResponse = null;
    int code;
    String responseBody = null;

    try {
        httpResponse = httpClient.execute(postMethod);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (httpResponse.getEntity() != null) {

        code = httpResponse.getStatusLine().getStatusCode();

        try {
            responseBody = EntityUtils.toString(httpResponse.getEntity());
        } catch (ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Response status code: " + code);
            logger.debug("Reponse body =" + responseBody);
        }

        responseMap.put("success", true);
        responseMap.put("statusCode", code);
        responseMap.put("responseBody", responseBody);

    } else {
        responseMap.put("success", false);
        responseMap.put("errorMessage", "Send failed (fill in exception)");
    }

    return responseMap;
}

From source file:info.guardianproject.cacert.CustomTrust.java

public CustomTrust(Context context, int rawResource, String password) throws IOException, KeyStoreException,
        KeyManagementException, NoSuchAlgorithmException, CertificateException {

    // Setup the SSL context to use the truststore
    ssl_ctx = SSLContext.getInstance("TLS");

    // Setup truststore
    KeyStore ksCACert = KeyStore.getInstance("BKS");
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    InputStream trustStoreStream = context.getResources().openRawResource(rawResource);
    ksCACert.load(trustStoreStream, password.toCharArray());

    //init factory with custom cacert
    trustManagerFactory.init(ksCACert);/*from  w w w  . j  av a  2s .com*/
    Log.d("SSL", "CACerts " + ksCACert.size());
    Log.d("SSL", "trustManagerFactory " + trustManagerFactory.getTrustManagers().length);

    // Setup client keystore
    /*
    KeyStore keyStore = KeyStore.getInstance("BKS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    InputStream keyStoreStream = context.getResources().openRawResource(R.raw.clientkeystore);
    keyStore.load(keyStoreStream, "testtest".toCharArray());
    keyManagerFactory.init(keyStore, "testtest".toCharArray());
    Log.d("SSL", "Key " + keyStore.size());
            
    Log.d("SSL", "keyManagerFactory " + keyManagerFactory.getKeyManagers().length);
    */

    //nothing implemented yet
    SecureRandom secRand = SecureRandom.getInstance(RANDOM_ALGORITHM);

    ssl_ctx.init(null, trustManagerFactory.getTrustManagers(), secRand);

    socketFactory = (SSLSocketFactory) ssl_ctx.getSocketFactory();

}

From source file:be.fgov.kszbcss.rhq.websphere.connector.security.TrustStoreManager.java

private KeyStore loadTrustStore() throws GeneralSecurityException, IOException {
    Lock lock = truststoreLock.readLock();
    lock.lock();/*from  w ww  .  j ava  2 s . co m*/
    try {
        KeyStore truststore = KeyStore.getInstance("JKS");
        if (truststoreFile.exists()) {
            if (log.isDebugEnabled()) {
                log.debug("Loading existing trust store from " + truststoreFile);
            }
            InputStream in = new FileInputStream(truststoreFile);
            try {
                truststore.load(in, new char[0]);
            } finally {
                in.close();
            }
            if (log.isDebugEnabled()) {
                log.debug("Trust store has " + truststore.size() + " existing entries");
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Trust store " + truststoreFile
                        + " doesn't exist yet; a new one will be created if necessary");
            }
            truststore.load(null);
        }
        return truststore;
    } finally {
        lock.unlock();
    }
}

From source file:org.mitre.svmp.net.SSLConfig.java

@SuppressLint("TrulyRandom")
private void doConfigure() throws KeyStoreException, CertificateException, NoSuchAlgorithmException,
        IOException, KeyManagementException {
    // find out if we should use the MemorizingTrustManager instead of the system trust store (set in Preferences)
    boolean useMTM = Utility.getPrefBool(context, R.string.preferenceKey_connection_useMTM,
            R.string.preferenceValue_connection_useMTM);

    // determine whether we should use client certificate authentication
    boolean useCertificateAuth = Constants.API_14 && (connectionInfo.getAuthType()
            & CertificateModule.AUTH_MODULE_ID) == CertificateModule.AUTH_MODULE_ID;

    // set up key managers
    KeyManager[] keyManagers = null;
    // if certificate authentication is enabled, use a key manager with the provided alias
    if (useCertificateAuth) {
        keyManagers = new KeyManager[] { new SVMPKeyManager(context, connectionInfo.getCertificateAlias()) };
    }/*w ww  . ja v  a2 s .c  o m*/

    // set up trust managers
    TrustManager[] trustManagers = null;

    KeyStore localTrustStore = KeyStore.getInstance("BKS");
    InputStream in = context.getResources().openRawResource(R.raw.client_truststore);
    localTrustStore.load(in, Constants.TRUSTSTORE_PASSWORD.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(localTrustStore);

    // 1) If "res/raw/client_truststore.bks" is not empty, use it as the pinned cert trust store (default is empty)
    // 2) Otherwise, if the "Show certificate dialog" developer preference is enabled, use that (default is disabled)
    // 3) Otherwise, use the default system trust store, consists of normal trusted Android CA certs
    if (localTrustStore.size() > 0) {
        // this means that "res/raw/client_truststore.bks" has been replaced with a trust store that is not empty
        // we will use that "pinned" store to check server certificate trust
        Log.d(TAG, "SSLConfig: Using static BKS trust store to check server cert trust");
        trustManagers = trustManagerFactory.getTrustManagers();
        // After switching to WebSockets, MTM causes the app to freeze; removed for now
    } else if (useMTM) {
        // by default useMTM is false ("Show certificate dialog" in developer preferences)
        // this creates a certificate dialog to decide what to do with untrusted certificates, instead of flat-out rejecting them
        Log.d(TAG,
                "SSLConfig: Static BKS trust store is empty but MTM is enabled, using MTM to check server cert trust");
        mtm = new MemorizingTrustManager(context);
        mtm.bindDisplayActivity(activity);
        trustManagers = new X509TrustManager[] { mtm };
    } else {
        Log.d(TAG,
                "SSLConfig: Static BKS trust store is empty and MTM is disabled, using system trust store to check server cert trust");
        // leaving trustManagers null accomplishes this
    }

    PRNGFixes.apply(); // fix Android SecureRandom issue on pre-KitKat platforms
    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, trustManagers, new SecureRandom());
}

From source file:mitm.djigzo.web.pages.certificate.CertificateImportKey.java

private void importPfx() throws KeyStoreException, NoSuchProviderException, SecurityFactoryFactoryException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableEntryException,
        WebServiceCheckedException {/*w w w.  j  a  v a2  s .com*/
    /*
     * To prevent timeouts on the SOAP connection we should upload the PFX file in batches if the PFX file
     * contains a large number of entries. The PFX file should therefore be opened. 
     */
    KeyStore allKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

    if (password == null) {
        password = "";
    }

    allKeys.load(file.getStream(), password.toCharArray());

    KeyAndCertificateWorkflow.MissingKey missingKey = ignoreMissingKey
            ? KeyAndCertificateWorkflow.MissingKey.SKIP_CERTIFICATE
            : KeyAndCertificateWorkflow.MissingKey.ADD_CERTIFICATE;

    int imported = 0;

    KeyStore batchKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");
    batchKeys.load(null, password.toCharArray());

    Enumeration<String> aliases = allKeys.aliases();

    KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(password.toCharArray());

    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();

        if (allKeys.isKeyEntry(alias)) {
            KeyStore.Entry entry = allKeys.getEntry(alias, passwordProtection);

            batchKeys.setEntry(alias, entry, passwordProtection);
        } else {
            Certificate certificate = allKeys.getCertificate(alias);

            batchKeys.setCertificateEntry(alias, certificate);
        }

        if (batchKeys.size() >= maxBatchSize) {
            imported += uploadKeyStore(batchKeys, missingKey, password);

            batchKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");
            batchKeys.load(null, password.toCharArray());
        }
    }

    /*
     * Check if there are still some entries left to add (happens when the number
     * of entries is not a multiple of maxBatchSize)
     */
    if (batchKeys.size() > 0) {
        imported += uploadKeyStore(batchKeys, missingKey, password);
    }

    this.importCount = imported;
}

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(", ");
        }/*from w w w  . j  a v a  2 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(", ");
        }// w  w w.j ava 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;
}

From source file:org.asynchttpclient.test.TestUtils.java

private static KeyManager[] createKeyManagers() throws GeneralSecurityException, IOException {
    KeyStore ks = KeyStore.getInstance("JKS");
    try (InputStream keyStoreStream = TestUtils.class.getClassLoader()
            .getResourceAsStream("ssltest-cacerts.jks")) {
        char[] keyStorePassword = "changeit".toCharArray();
        ks.load(keyStoreStream, keyStorePassword);
    }/*w w w  .  ja  v  a2s  .  co m*/
    assert (ks.size() > 0);

    // Set up key manager factory to use our key store
    char[] certificatePassword = "changeit".toCharArray();
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, certificatePassword);

    // Initialize the SSLContext to work with our key managers.
    return kmf.getKeyManagers();
}

From source file:org.asynchttpclient.test.TestUtils.java

private static TrustManager[] createTrustManagers() throws GeneralSecurityException, IOException {
    KeyStore ks = KeyStore.getInstance("JKS");
    try (InputStream keyStoreStream = TestUtils.class.getClassLoader()
            .getResourceAsStream("ssltest-keystore.jks")) {
        char[] keyStorePassword = "changeit".toCharArray();
        ks.load(keyStoreStream, keyStorePassword);
    }//from   w w  w .j a  va  2  s.com
    assert (ks.size() > 0);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    return tmf.getTrustManagers();
}

From source file:org.codice.ddf.security.common.Security.java

/**
 * Gets the {@link Subject} associated with this system. Uses a cached subject since the subject
 * will not change between calls./*from  ww  w  .  j  a  va 2 s . com*/
 *
 * @return system's {@link Subject}
 */
public synchronized Subject getSystemSubject() {

    if (!tokenAboutToExpire(cachedSystemSubject)) {
        return cachedSystemSubject;
    }

    KeyStore keyStore = getSystemKeyStore();
    String alias = null;
    Certificate cert = null;
    try {
        if (keyStore != null) {
            if (keyStore.size() == 1) {
                alias = keyStore.aliases().nextElement();
            } else if (keyStore.size() > 1) {
                alias = getCertificateAlias();
            }
            cert = keyStore.getCertificate(alias);
        }
    } catch (KeyStoreException e) {
        LOGGER.error("Unable to get certificate for alias [{}]", alias, e);
        return null;
    }

    if (cert == null) {
        LOGGER.error("Unable to get certificate for alias [{}]", alias);
        return null;
    }

    PKIAuthenticationTokenFactory pkiTokenFactory = createPKITokenFactory();
    PKIAuthenticationToken pkiToken = pkiTokenFactory.getTokenFromCerts(
            new X509Certificate[] { (X509Certificate) cert }, PKIAuthenticationToken.DEFAULT_REALM);
    if (pkiToken != null) {
        SecurityManager securityManager = getSecurityManager();
        if (securityManager != null) {
            try {
                cachedSystemSubject = securityManager.getSubject(pkiToken);
            } catch (SecurityServiceException sse) {
                LOGGER.error("Unable to request subject for system user.", sse);
            }
        }
    }
    return cachedSystemSubject;
}