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.pieframework.runtime.utils.CertificateUtils.java

public static X509Certificate getCertificate(File certificateFile, String pass, String certAlias) {
    X509Certificate certificate = null;

    try {// w w  w .ja va 2 s  .  c  om
        FileInputStream cert = new FileInputStream(certificateFile);
        KeyStore pfxStore = KeyStore.getInstance("pkcs12");
        pfxStore.load(cert, pass.toCharArray());
        if (StringUtils.empty(certAlias) && pfxStore.size() > 0) {
            certAlias = pfxStore.aliases().nextElement();
        }
        certificate = (X509Certificate) pfxStore.getCertificate(certAlias);
        cert.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return certificate;
}

From source file:com.thoughtworks.go.security.AuthSSLKeyManagerFactory.java

private void logKeyStore(KeyStore store) throws KeyStoreException {
    LOG.trace("Certificates count: " + store.size());
    Enumeration aliases = store.aliases();
    while (aliases.hasMoreElements()) {
        String alias = (String) aliases.nextElement();
        Certificate[] certs = store.getCertificateChain(alias);
        if (certs != null) {
            LOG.debug("Certificate chain '" + alias + "':");
            for (int c = 0; c < certs.length; c++) {
                if (certs[c] instanceof X509Certificate) {
                    X509Certificate cert = (X509Certificate) certs[c];
                    LOG.trace(" Certificate " + (c + 1) + ":");
                    LOG.trace("  Subject DN: " + cert.getSubjectDN());
                    LOG.trace("  Signature Algorithm: " + cert.getSigAlgName());
                    LOG.trace("  Valid from: " + cert.getNotBefore());
                    LOG.trace("  Valid until: " + cert.getNotAfter());
                    LOG.trace("  Issuer: " + cert.getIssuerDN());
                }/*from  w w w  .j a v  a 2  s  .c  om*/
            }
        }
    }
}

From source file:com.github.jmkgreen.keystore.mongo.KeyStoreRest.java

@GET
@Path("create-new-key")
public void createNewKey(@QueryParam("keystoreName") String keystoreName,
        @QueryParam("keystorePassword") String password, @QueryParam("keyName") String keyName,
        @QueryParam("keyPassword") String keyPassword)
        throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException {
    KeyStore store = keyStoreRepository.load(keystoreName, "JCEKS", password);
    LOG.info("Creating a new key within a store currently holding " + store.size() + " keys.");
    AesCipherService cipherService = new AesCipherService();
    Key key = cipherService.generateNewKey(256);
    store.setKeyEntry(keyName, key, keyPassword.toCharArray(), null);
    keyStoreRepository.createOrUpdate(keystoreName, password.toCharArray(), store);
    LOG.info("Stored Key within a KeyStore currently holding " + store.size() + " keys.");
}

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

public void execute(TrustStoreAction action, boolean readOnly) throws Exception {
    Lock lock = readOnly ? truststoreLock.readLock() : truststoreLock.writeLock();
    lock.lock();/*from  w  w w. ja  v  a  2s .  c om*/
    try {
        KeyStore truststore = loadTrustStore();
        action.execute(truststore);
        if (!readOnly) {
            if (log.isDebugEnabled()) {
                log.debug("Writing trust store with " + truststore.size() + " entries to " + truststoreFile);
            }
            OutputStream out = new FileOutputStream(truststoreFile);
            try {
                truststore.store(out, new char[0]);
            } finally {
                out.close();
            }
            reloadTrustManager();
        }
    } finally {
        lock.unlock();
    }
}

From source file:com.emc.cto.ridagent.rid.test.TestScript.java

public static String httpSend(String output, String destURL) throws ParserConfigurationException, SAXException {

    /* Set up TLS mutual authentication */

    KeyStore keystore = null;
    String docid = null;// w  w  w . jav  a  2s . c  o m
    try {
        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();
    }

    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 */

    Map<String, Object> responseMap = new HashMap<String, Object>();

    HttpEntity request = new StringEntity(output, 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;

    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 {
            InputStream xml = httpResponse.getEntity().getContent();

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xml);
            docid = doc.getElementsByTagName("iodef:IncidentID").item(0).getTextContent();
            System.out.println("ID of the newly created document   " + docid);
        } catch (ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

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

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

    return docid;
}

From source file:mitm.application.djigzo.ca.PFXMailBuilderTest.java

@Test
public void testReplacePFX() throws Exception {
    byte[] pfx = IOUtils.toByteArray(new FileInputStream(testPFX));

    PFXMailBuilder builder = new PFXMailBuilder(IOUtils.toString(new FileInputStream(templateFile)),
            templateBuilder);/*from w  w  w .  java 2  s  .c om*/

    String from = "123@test.com";

    builder.setFrom(new InternetAddress(from, "test user"));
    builder.setPFX(pfx);

    MimeMessage message = builder.createMessage();

    assertNotNull(message);

    MailUtils.writeMessage(message, new File(tempDir, "testReplacePFX.eml"));

    /*
     * Check if the PFX has really been replaced
     */
    byte[] newPFX = getPFX(message);

    KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

    keyStore.load(new ByteArrayInputStream(newPFX), "test".toCharArray());

    assertEquals(22, keyStore.size());
}

From source file:mitm.application.djigzo.ca.PFXMailBuilderTest.java

@Test
public void testReplacePFXMissingMarker() throws Exception {
    byte[] pfx = IOUtils.toByteArray(new FileInputStream(testPFX));

    PFXMailBuilder builder = new PFXMailBuilder(
            IOUtils.toString(new FileInputStream("test/resources/templates/mail-pfx-no-marker.ftl")),
            templateBuilder);//from  w  ww.j  av  a 2s . co m

    String from = "123@test.com";

    builder.setFrom(new InternetAddress(from, "test user"));
    builder.setPFX(pfx);
    builder.addProperty("test", "new value");

    MimeMessage message = builder.createMessage();

    assertNotNull(message);

    MailUtils.writeMessage(message, new File(tempDir, "testReplacePFXMissingMarker.eml"));

    assertEquals("new value", message.getHeader("X-TEST", ","));

    /*
     * Check if the PFX has really been replaced
     */
    byte[] newPFX = getPFX(message);

    KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

    keyStore.load(new ByteArrayInputStream(newPFX), "test".toCharArray());

    assertEquals(22, keyStore.size());
}

From source file:mitm.application.djigzo.ca.PFXMailBuilderTest.java

@Test
public void testReplacePFXSendSMSFalse() throws Exception {
    byte[] pfx = IOUtils.toByteArray(new FileInputStream(testPFX));

    PFXMailBuilder builder = new PFXMailBuilder(IOUtils.toString(new FileInputStream(templateFile)),
            templateBuilder);/*from   ww w. j av a 2 s  . c  o  m*/

    String from = "123@test.com";

    builder.setFrom(new InternetAddress(from, "test user"));
    builder.setPFX(pfx);
    builder.addProperty("sendSMS", false);

    MimeMessage message = builder.createMessage();

    assertNotNull(message);

    MailUtils.writeMessage(message, new File(tempDir, "testReplacePFXSendSMSFalse.eml"));

    Multipart mp;

    mp = (Multipart) message.getContent();

    BodyPart textPart = mp.getBodyPart(0);

    assertTrue(textPart.isMimeType("text/plain"));

    String body = (String) textPart.getContent();

    assertFalse(body.contains("was sent to you by SMS"));

    /*
     * Check if the PFX has really been replaced
     */
    byte[] newPFX = getPFX(message);

    KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

    keyStore.load(new ByteArrayInputStream(newPFX), "test".toCharArray());

    assertEquals(22, keyStore.size());
}

From source file:mitm.application.djigzo.ws.impl.KeyAndCertificateWorkflowWSImpl.java

private int addKeysAction(byte[] encodedPFX, String password, KeyAndCertificateWorkflow.MissingKey missingKey)
        throws WebServiceCheckedException {
    ByteArrayInputStream bis = new ByteArrayInputStream(encodedPFX);

    KeyStore keyStore;

    try {/*from   w ww  . j a v  a 2 s  .co m*/
        SecurityFactory securityFactory = SecurityFactoryFactory.getSecurityFactory();

        keyStore = securityFactory.createKeyStore("PKCS12");

        keyStore.load(bis, password.toCharArray());

        if (keyStore.size() == 0) {
            throw new WebServiceCheckedException("No keys found in encodedPFX.");
        }

        return keyAndCertificateWorkflow.importKeyStore(keyStore, missingKey);
    } catch (CertificateException e) {
        throw new WebServiceCheckedException(e);
    } catch (NoSuchProviderException e) {
        throw new WebServiceCheckedException(e);
    } catch (KeyStoreException e) {
        throw new WebServiceCheckedException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new WebServiceCheckedException(e);
    } catch (IOException e) {
        throw new WebServiceCheckedException(e);
    }
}

From source file:mitm.application.djigzo.ca.PFXMailBuilderTest.java

@Test
public void testReplacePFXSendSMSTrue() throws Exception {
    byte[] pfx = IOUtils.toByteArray(new FileInputStream(testPFX));

    PFXMailBuilder builder = new PFXMailBuilder(IOUtils.toString(new FileInputStream(templateFile)),
            templateBuilder);//w  w w . j  a v a 2  s .c  o  m

    String from = "123@test.com";

    builder.setFrom(new InternetAddress(from, "test user"));
    builder.setPFX(pfx);
    builder.addProperty("sendSMS", true);
    builder.addProperty("phoneNumberAnonymized", "1234***");
    builder.addProperty("id", "0987");

    MimeMessage message = builder.createMessage();

    assertNotNull(message);

    MailUtils.writeMessage(message, new File(tempDir, "testReplacePFXSendSMSTrue.eml"));

    Multipart mp;

    mp = (Multipart) message.getContent();

    BodyPart textPart = mp.getBodyPart(0);

    assertTrue(textPart.isMimeType("text/plain"));

    String body = (String) textPart.getContent();

    assertTrue(body.contains("was sent to you by SMS"));

    /*
     * Check if the PFX has really been replaced
     */
    byte[] newPFX = getPFX(message);

    KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

    keyStore.load(new ByteArrayInputStream(newPFX), "test".toCharArray());

    assertEquals(22, keyStore.size());
}